// JavaScript Document



var editphygroupid;

$(document).ready(function() {
  var module_alert = $("#module").val(); //name of the module or functionality to display in alert box
  var action = module_alert;
  if(action == "Speciality"){
    action = "Specialty";
  }

  //function added by karthikeyan on 29/12/2009 for activating the speciality by clicking activate button on the top
  $("#physician-activate").click(function() {
    var checkbox_values = [];
    //var alert_physician;
    $('input[@name=checkBoxList]:checked').each(function(i){
      checkbox_values[i] = $(this).val();//store the selected values in an array
    });
    if(checkbox_values.length == 0){
      openAlertDialog(400, 130, 'Information', 'Please select atleast one ' + action.toLowerCase() + ' to activate','information');
      return false;
    }
    var n =0;
    for(i=0;i<checkbox_values.length;i++){
      var elem_id = "#speciality_statusCode";
      if(action=="Physician"){
        elem_id="#physician_status_";
      }
      var physicianlocatoractive = $(elem_id+checkbox_values[i]).html();
      n = physicianlocatoractive.search('Active');
      if(n >= 0 ){
        openAlertDialog(400, 130, 'Information', 'Please select the '+action.toLowerCase()+' which is in Inactive status','information');
        return false;
      }
    }

    activateItems(checkbox_values,module_alert);
    return false;
  });
  
  //function added by karthikeyan on 29/12/2009 for de-activating the speciality by clicking de-activate button on the top
  $("#physician-deactivate").click(function() {
    var checkbox_values = [];
    $('input[@name=checkBoxList]:checked').each(function(i){
      checkbox_values[i] = $(this).val();//store the selected values in an array
    });
    if(checkbox_values.length == 0){
      openAlertDialog(400, 130, 'Information', 'Please select atleast one ' + action.toLowerCase() + ' to deactivate','information');
      return false;
    }

    var n =0;
    for(i=0;i<checkbox_values.length;i++){
      var elem_id="#speciality_statusCode";
      if(action=="Physician"){
        elem_id="#physician_status_";
      }
      var physicianlocatorinactive = $(elem_id+checkbox_values[i]).html();
      n = physicianlocatorinactive.search('Inactive');
      if(n >= 0 ){
        openAlertDialog(400, 130, 'Information', 'Please select the ' + action.toLowerCase() + ' which is in Active status','information');
        return false;
      }
    }
    deactivateItems(checkbox_values,module_alert);
    return false;
  });
  
  //function added by karthikeyan on 29/12/2009 for activating the group by clicking activate button on the top
  $("#group-activate").click(function() {
    var checkbox_values = [];
    //var alert_physician;
    $('input[@name=checkBoxList]:checked').each(function(i){
      checkbox_values[i] = $(this).val();//store the selected values in an array
      
    });
    if(checkbox_values.length == 0){
      openAlertDialog(400, 130, 'Error Message', 'Please select atleast one ' + action.toLowerCase() + ' to activate', 'information');
      return false;
    }

    var n =0;
    for(i=0;i<checkbox_values.length;i++){
      var grouplocatoractive;
      grouplocatoractive = $('#group_statusCode'+checkbox_values[i]).html();
      n = grouplocatoractive.search('Active');
      if(n >= 0 ){
        openAlertDialog(400, 130, 'Error Message', 'Please select the '+action.toLowerCase()+' which is in Inactive status', 'information');
        return false;
      }
    }

    activateItems(checkbox_values,module_alert);
    return false;
  });

  //function added by karthikeyan on 29/12/2009 for de-activating the group by clicking de-activate button on the top
  $("#group-deactivate").click(function() {
    var checkbox_values = [];
    $('input[@name=checkBoxList]:checked').each(function(i){
      checkbox_values[i] = $(this).val();//store the selected values in an array
    });
    if(checkbox_values.length == 0){
      openAlertDialog(400, 130, 'Error Message', 'Please select atleast one ' + module_alert.toLowerCase() + ' to deactivate');
      return false;
    }

    var n =0;
    for(i=0;i<checkbox_values.length;i++){
      var grouplocatorinactive;
      grouplocatorinactive = $('#group_statusCode'+checkbox_values[i]).html();
      n = grouplocatorinactive.search('Inactive');
      if(n >= 0 ){
        openAlertDialog(400, 130, 'Error Message', 'Please select the ' + module_alert.toLowerCase() + ' which is in Active status');
        return false;
      }
    }
    deactivateItems(checkbox_values,module_alert);
    return false;
  });

  //manage auto reply in detail page
  $("#warmhandoffautoreplybtn").click(function() {
    openDialog(managewarmhandoffnotification,'1',780,510,'Manage Warm Handoff Notification');

  });
  
  //Function to date specialty
  $('#edit-speciality-search-date').datepicker({
    dateFormat:'mm-dd-yy'
  });

  $('#edit-handoffreport-start-date').datepicker({
    dateFormat:'mm-dd-yy'
  });

  $('#edit-handoffreport-end-date').datepicker({
    dateFormat:'mm-dd-yy'
  });

  if($('#edit-invite-search-date')!=null){
    $('#edit-invite-search-date').datepicker({
      dateFormat:'mm-dd-yy'
    });
  }


  $('#warmhandoff-export').click(function(){
    var pno = $('#hid_pageno').val();    
    var physid=$('#contact_physician_id').val();   
    window.location=baseurl+'physician_locator/export_reports/'+physid+"/"+pno;
  });

 
  $("#edit-apply").click(function () {
    applyAction(1,$(this).attr('actionitem'));
    return false;
  });

   
});


//Function to save auto reply for subjects
function warmhandoffautoreply () {
  var fname = $('#edit-warmhandoff-from-name').val();
  var email = $('#edit-warmhandoff-from-email').val();
  var reply = $('#edit-warmhandoff-reply-to').val();
  var local = "EN";
  var subject = $('#edit-warmhandoff-subject').val();
  var spec=$('#edit-notification-speciality').val();
  
  
        
  var resp = editor.getData();

 
  var str = "";
  if($.trim(spec) == -1){
     
    str += "Please select the speciality";
  }
	
 
  if($.trim(fname)=="")
  {
    if(str!="")
      str+= "<br/>";
    str += "From Name should not be empty";
  }
 
		
  if($.trim(email) == ""){
    if(str!="")
      str+= "<br/>";
    str += "From Email Address should not be empty";
  }
  if ($.trim(email) != "") {
    if (!validateEmail(email)) {
      if(str!="")
        str+= "<br/>";
      str += "From Email Address is an invalid email address";
    }
  }
  if($.trim(reply)==""){
    if(str!="")
      str+= "<br/>";
    str += "Reply To should not be empty";
  }
  if ($.trim(reply) != "") {
    if (!validateEmail(reply)) {
      if(str!="")
        str+= "<br/>";
      str += "Reply To is an invalid email address";
    }
  }
  if($.trim(local)==""){
    if(str!="")
      str+= "<br/>";
    str += "Expired Date should not be empty";
  }
  if($.trim(subject)==""){
    if(str!="")
      str+= "<br/>";
    str += "Subject should not be empty";
  }
  if($.trim(resp)=="" || $.trim(resp)=="<br />"){
    if(str!="")
      str+= "<br/>";
    str += "Content should not be empty";
  }
	
  if (str != "") {
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }
	
	
		
  $('#dialog').html('<div style="padding-top:130px; padding-left:345px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/warmhandoffnotification/save',
    data : "fname="+fname+"&email="+email+"&reply="+reply+"&local="+local+"&subject="+subject+"&resp="+resp+"&spec="+spec,
    async : true,
    cache : false,
    success : function (msg) {	
      if(trim(msg)== 'Success') {
        $("#dialog").dialog("destroy");
        openAlertDialog(300, 130, 'Information', 'Physician notification message saved successfully','success');
      }
      else
      {
        $('#dialog').dialog('destroy');
        openAlertDialog(300, 130, 'Error', 'Error in sending physician notification message');
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}



var editor;
function managewarmhandoffnotification(){
 
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/warmhandoffnotification/',
    async : true,
    cache : false,
    success : function (msg) {
      //diaply the returned html in the dialog window
      $('#dialog').html(msg);
      $('.ui-dialog').css("filter","");
      //add editor to the textarea
      if(!editor){
        editor = CKEDITOR.replace('edit-warmhandoff-response',{
          skin : 'v2',
          resize_enabled:false,
          enterMode: Number(2),
          removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
        });
      }else{
        if (CKEDITOR.instances['edit-warmhandoff-response']) {
          CKEDITOR.remove(CKEDITOR.instances['edit-warmhandoff-response']);
        }
        editor = CKEDITOR.replace( 'edit-warmhandoff-response',{
          skin : 'v2',
          resize_enabled:false,
          enterMode: Number(2),
          removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
        });
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}



//function added by karthikeyan on 29/12/2009 for deactivating the selected specialties and groups
function deactivateItems(checkbox_values, module_alert){
  if(module_alert == "Speciality"){
    openConfirmBox(function(){
      $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
      $.ajax({
        type: "POST",
        url : baseurl+'physician_locator/specialityactions/deactivate',
        data: '&catvalues=' + checkbox_values,
        success: function(res){
          $('#alertdialog').dialog('destroy');
          if(res == 'Success'){
            $('input[name=checkAll]').attr('checked', false);
            //reopen_dialog(300,125,"Successfully Updated");
            var pageno   = $('#hid_pageno').val();
            var module   = $('#module').val();
           
            applyspecialityAction(pageno,'view_speciality');
            $('#dialog').dialog('destroy');
            openAlertDialog(300, 140, 'Information', 'Selected specialties deactivated successfully','success');
          //$('input[name=checkAll]').attr('checked', false);

          }
          else{
            $('#dialog').dialog('destroy');
            openAlertDialog(300, 140, 'Error', 'Error in deactivating the specialties');
          }
        },
        error : function (res) {
          handleRequestError(res);
        }
      });
    },300,130,"Confirm Deactivate","Do you want to Deactivate?");
    return false;
  }else if(module_alert=="Physician"){
    openConfirmBox(function(){
      $('#alertdialog').dialog('destroy');
      $.ajax({
        type : "POST",
        url : baseurl+"physician_locator/actions/deactivate",
        data: '&checkbox_values=' + checkbox_values,
        async : true,
        cache : false,
        success : function (msg) {
          if(msg=="success"){
            var pageno   = $('#hid_pageno').val();
            applyphysicianAction(pageno,'physician');
            openAlertDialog(300, 140, 'Information', 'Selected ' + module_alert.toLowerCase() + ' deactivated successfully','success');
          }else{
            openAlertDialog(300, 140, 'Error', 'Error in activating the ' + module_alert.toLowerCase() + '');
          }
        }
      });
    },300,130,"Confirm Deactivate","Do you want to Deactivate?");
  }
  else{	    
    openConfirmBox(function(){
      $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
      $.ajax({
        type: "POST",
        url : baseurl+'physician_locator/groupactions/deactivate',
        data: '&groupvalues=' + checkbox_values,
        success: function(res){
          $('#alertdialog').dialog('destroy');
          if(res == 'Success'){
            var pageno   = $('#hid_pageno').val();
            applygroupAction(pageno,"view_group");
            openAlertDialog(300,140, 'Deactivated', 'Selected groups deactivated successfully','success');
            $('input[name=checkAll]').attr('checked', false);
          }
          else{
            $('#dialog').dialog('destroy');
            openAlertDialog(300, 140, 'Error', 'Error in deactivating the groups');
          }
        },
        error : function (res) {
          handleRequestError(res);
        }
      });
    },300,130,"Confirm Deactivate","Do you want to Deactivate?");
    return false;
  }
}


//function added by karthikeyan on 29/12/2009 for activating the selected specialties and groups
function activateItems(checkbox_values, module_alert){
  if(module_alert == "Speciality"){
    var action = module_alert;
    if(action == "Speciality"){
      action = "Specialty";
    }
    openConfirmBox(function(){
      $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');

      $.ajax({
        type: "POST",
        url : baseurl+'physician_locator/specialityactions/activate',
        data: '&catvalues=' + checkbox_values,
        success: function(res){
          $('#alertdialog').dialog('destroy');
          if(res == 'Success'){
            $('input[name=checkAll]').attr('checked', false);
            //reopen_dialog(300,125,"Successfully Updated");
            var pageno   = $('#hid_pageno').val();
            //var module   = $('#module').val();
            applyspecialityAction(pageno,'view_speciality');
            $('#dialog').dialog('destroy');
            openAlertDialog(300, 140, 'Information', 'Selected ' + action.toLowerCase() + ' activated successfully','success');
          //$('input[name=checkAll]').attr('checked', false);
          }
          else{
            //reopen_dialog(300,125,"Error");
            $('#dialog').dialog('destroy');
            openAlertDialog(300, 140, 'Error', 'Error in activating the ' + action.toLowerCase() + '');
          }
        },
        error : function (res) {
          handleRequestError(res);
        }
      });
    },300,130,"Confirm Activate","Do you want to Activate?");
    return false;
  }else if(module_alert=="Physician"){
    openConfirmBox(function(){
      $('#alertdialog').dialog('destroy');
      $.ajax({
        type : "POST",
        url : baseurl+"physician_locator/actions/activate",
        data: '&checkbox_values=' + checkbox_values,
        async : true,
        cache : false,
        success : function (msg) {
          if(msg=="success"){
            var pageno   = $('#hid_pageno').val();
            applyphysicianAction(pageno,'physician');
            openAlertDialog(300, 140, 'Information', 'Selected ' + module_alert.toLowerCase() + ' activated successfully','success');
          }else{
            openAlertDialog(300, 140, 'Error', 'Error in activating the ' + action.toLowerCase() + '');
          }
        }
      });
    },300,130,"Confirm Activate","Do you want to Activate?");
  }
  else{
    openConfirmBox(function(){
      $('#dialog').html('<div style="padding-top:50px; padding-left:260px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
      $.ajax({
        type: "POST",
        url : baseurl+'physician_locator/groupactions/activate',
        data: '&groupvalues=' + checkbox_values,
        success: function(res){
          $('#alertdialog').dialog('destroy');
          if(res == 'Success'){
            var pageno   = $('#hid_pageno').val();
            applygroupAction(pageno,"view_group");
            openAlertDialog(300, 140, 'Activated', 'Selected groups activated successfully','success');
            $('input[name=checkAll]').attr('checked', false);
          }
          else{
            $('#dialog').dialog('destroy');
            openAlertDialog(300, 140, 'Error', 'Error in activating the group');
          }
        },
        error : function (res) {
          handleRequestError(res);
        }
      });
    },300,130,"Confirm Activate","Do you want to Activate?");
    return false;
  }
}


//function to activate or deactivate physician
function activeDeactive(ok, fn, id, action, mode) { 
  var listpage;
  if(action=='actions'){
    listpage = '';
  }
  if(action=='specialityactions'){
    listpage = '/view_speciality';
  }
  if(action=='groupactions'){
    listpage = '/view_group';
  }
  if (ok) {
    $(ok).dialog('destroy');
  }
  $("#pagingdivtop").html("");
  $("#pagingdivbottom").html("");
  var limit = $('#hid_limit').val();
	  
  var counter = $('#hid_totalRec').val();
  $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');//AJAX call to update the status of the messages
	
  $.ajax({
    type : "POST",
    url : baseurl+"physician_locator/"+action+"/"+(fn == "active" ? "activate" : "deactivate"),
    data : "checkbox_values="+id,
    async : false,
    cache : false,
    success : function (msg){
      if (msg == "success") {
        var tot_sel = (id+"").split(",");
        reloadListingData(limit,1,"", parseInt(counter, 10)-tot_sel.length,baseurl+"physician_locator"+listpage,"page");
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function applyAction(pageno,action){ 


  if(action=='view_speciality'){
    $('#checkAll').is(':checked')
    $('#checkAll').attr('checked', false);
    applyspecialityAction(pageno, action);
  }
  else if(action=='view_group'){
    applygroupAction(pageno, action);
  }else if(action=='view_invites'){
    applyinviteAction(pageno, action);
  }else if(action=='view_warmhandoff'){
    applywarmhandoffaction(pageno, action);
  }else{
    applyphysicianAction(pageno, action);
  }
}



function applywarmhandoffaction(pageno, action){  
  
  var data = filterdata_view_warmhandoff();
  $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").html('');
  $("#pagingdivbottom").html('');
  $.ajax({
    type : "POST",
    url : baseurl+"physician_locator/actions/filter"+(action=='view_warmhandoff'?'/view_warmhandoff':''),
    data : data+(pageno>1?'&page_no='+pageno:''),
    async : false,
    cache : false,
    success : function (msg) {
        
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = pageno;
      var counter = $('#hid_totalRec').val();

      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applywarmhandoffaction('+(page-1)+',\''+action+'\')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "applywarmhandoffaction('+(parseInt(page, 10)+1)+',\''+action+'\')" class="red">Next >></a>';
          
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
      
      }
    }
  });
}




function applygroupAction(pageno, action){
  var data = filterdata_view_group();
  var sort = $('#hid_sort').val();

  $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").html('');
  $("#pagingdivbottom").html('');
 
  $.ajax({
    type : "POST",
    url : baseurl+"physician_locator/actions/filter"+(action=='view_group'?'/view_group':''),
    data : data+(pageno>1?'&page_no='+pageno:'')+(sort!=""?'&sorting='+sort:''),
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = parseInt(pageno);
      var counter = $('#hid_totalRec').val();
      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applygroupAction('+(page-1)+',\''+action+'\')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "applygroupAction('+(parseInt(page, 10)+1)+',\''+action+'\')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#hid_pageno").val(page);
      }
    }
  });
}


function applyspecialityAction(pageno, action){
  
  var data = filterdata_view_speciality();
  var sort = $('#hid_sort').val();
 
  $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").html('');
  $("#pagingdivbottom").html('');
  
  $.ajax({
    type : "POST",
    url : baseurl+"physician_locator/actions/filter"+(action=='view_speciality'?'/view_speciality':''),
    data : data+(pageno>1?'&page_no='+pageno:'')+(sort!=""?'&sorting='+sort:''),
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = parseInt(pageno);
      var counter = $('#hid_totalRec').val();
    
      if(counter>0){
        
        var str="";
        var to = page*limit;
        
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyspecialityAction('+(page-1)+',\''+action+'\')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "applyspecialityAction('+(parseInt(page, 10)+1)+',\''+action+'\')" class="red">Next >></a>';
        }
        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#hid_pageno").val(page);
      }
    }
  });
}

function applyphysicianAction(pageno, action){
  var data = filterdata_physician_locator();
  $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").html('');
  $("#pagingdivbottom").html('');
  var sort = $('#hid_sort').val();
  $.ajax({
    type : "POST",
    url : baseurl+"physician_locator/actions/filter",
    data : data + (pageno>1?'&page_no='+pageno:'')+(sort?'&sorting='+sort:''),
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = pageno;
      var counter = $('#hid_totalRec').val();
      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyphysicianAction('+(page-1)+',\''+action+'\')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "applyphysicianAction('+(parseInt(page, 10)+1)+',\''+action+'\')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
      }
    }
  });
}

function applyinviteAction(pageno, action){
  var data = filterdata_view_invites();
  $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").html('');
  $("#pagingdivbottom").html('');
  $.ajax({
    type : "POST",
    url : baseurl+"physician_locator/actions/filter/view_invites",
    data : data + (pageno>1?'&page_no='+pageno:''),
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      var limit = $('#hid_limit').val();
      var page = pageno;
      var counter = $('#hid_totalRec').val();
      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "applyinviteAction('+(page-1)+',\''+action+'\')" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "applyinviteAction('+(parseInt(page, 10)+1)+',\''+action+'\')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
      }
    }
  });
}
//function to reload Physician list through AJAX
function reloadPhysicianList (limit, page, action, counter, locate) {
  //Call the AJAX functionality and return the result
  if(locate=='view_speciality'){
    locatevalue =  '/view_speciality';
  }else if(locate=='view_group'){
    locatevalue =  '/view_group';
  }else if(locate=='view_invites'){
    locatevalue =  '/view_invites';
  }

  else if(locate =='handoffreports'){
    var specid=$('#edit-basic-specialty').val();
    locatevalue =  '/handoffreports/'+specid;
  }

  else if(locate =='patientdetails'){
    var physiid=$('#contact_physician_id').val();
   
    locatevalue =  '/patientdetails/'+physiid;
  }
  else{
    locatevalue =  '';
  }
  
  $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $("#pagingdivtop").html('');
  $("#pagingdivbottom").html('');
  $.ajax({
    type : "POST",
    url : baseurl+"physician_locator"+(locatevalue)+"?limit="+limit+"&page="+page+"&mode=ajax",
    async : false,
    cache : false,
    success : function (msg) {
      $("#listingResultset").html(msg);
      if(counter>0){
        var str="";
        var to = page*limit;
        str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
        if (page > 1) {
          str += '<a href="javascript:void(0)" onclick = "reloadPhysicianList('+limit+', '+(page-1)+', \'previous\', '+counter+', \''+locate+'\' )" class="red"><< Previous</a>';
        }

        if (to < counter) {
          str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "reloadPhysicianList('+limit+', '+(page+1)+', \'next\', '+counter+', \''+locate+'\')" class="red">Next >></a>';
        }

        $("#pagingdivtop").html(str);
        $("#pagingdivbottom").html(str);
        $("#hid_pageno").val(page);
      }
    }
  });
}

function addspecialty(){
  $("#cancelId").val("");

  openDialog(addspecialitydialog, '', 520,290, 'Create Specialty');
}


    

function addspecialitydialog(){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/create_speciality',
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
     
      if ($("#cancelId").val() == "cancel"){
        $("#edit-check-invite").attr('checked','checked');
        $("#spec_create").show();
        $("#spec_create_createris").hide();
      }else{
        $('#edit-specialityname').val("");
        //$("#edit-check-invite").attr('checked',false);
        $("#edit-check-invite").attr('checked',true);
        $('#edit-status').val("");
        $('#edit-specialitydesc').val("");
      }
     
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function closeDialog(testId){
  $('#dialog').dialog('destroy');
  makeArchived(testId);
}

/*Function to open popup window */
/*function actionUrl(actionname,title,type,width,height,specialityid){
  $('#dialog').dialog('destroy');
  if(type=='create'){
    openDialog(actionname,specialityid,width,height,title);
  }
}*/

/*Function to add location  */
function addlocation(){
  var groupid   = $("#edit-groupid").val();
  var specialtyid = $("#edit-speciality").val();
  var firstname   = $("#edit-firstname").val();
  var lastname    = $("#edit-lastname").val();
  var title       = $("#edit-title").val();
  var professionaltitle = $("#edit-professionaltitle").val();
  var email      = $("#edit-email").val();
  var websiteurl = $("#edit-websiteurl").val();
  var npid       = $("#edit-npid").val();
  var phone      = $("#edit-phone").val();
  var phonetype  = $("#edit-phonetype").val();
  var phone1      = $("#edit-phone1").val();
  var phonetype1  = $("#edit-phonetype1").val();
  var phone2      = $("#edit-phone2").val();
  var phonetype2  = $("#edit-phonetype2").val();
  var status     = $("#edit-status").val();
  var radiogender = document.getElementsByName("gender");
  
  websiteurl = websiteurl.replace(new RegExp(/^http\:\/\/|^https\:\/\/|^ftp\:\/\//i),"");
  var radiogenderValue = 'M';
  for(i=0; i < radiogender.length; i++){
    if (radiogender[i].checked == true) {
      radiogenderValue = radiogender[i].value;
    }
  }
  var radioagree = $("#edit-agreed-1").get(0);
  var radioagreeValue = ""
  if(radioagree.checked){
    radioagreeValue = "1";
  }
  
  var locationid = "";
  $(".location-class:checked").each( function () {
    if(locationid!="")
      locationid += ",";
    var result = $(this).val();
    locationid =locationid+result;
  });

  var physicianformdata = '{"firstname":"'+firstname+'","lastname":"'+lastname+'","title":"'+title+'","proftitle":"'+professionaltitle+'","email":"'+email+'","websiteurl":"'+ websiteurl+'","npid":"'+npid+'","phone":"'+phone+'","phonetype":"'+phonetype+'","phone1":"'+phone1+'","phonetype1":"'+phonetype1+'","phone2":"'+phone2+'","phonetype2":"'+phonetype2+'","gender":"'+radiogenderValue+'","status":"'+status+'","agree":"'+radioagreeValue+'","locations":"'+locationid+'"}';

  reopen_dialog(650,400,"Add Location");
  addlocationdialog(groupid , specialtyid, physicianformdata);
}

function addlocationdialog(groupid , specialtyid, physicianformdata){
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/create_group/location',
    data: "groupid="+groupid+"&specialtyid="+specialtyid+"&formdata="+encodeURIComponent(physicianformdata),
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function ltrim ( s ){
  return s.replace( /^\s*/, "" );
}


/*Function to create physician */
function createPhysician(){
  $('#dialog').dialog('destroy');
  openDialog(createphysiciandialog, 0, 650, 545, "Create Physician");
}

/*Function to Edit physician */
function editPhysician(id){
  reopen_dialog(650, 480, "Edit Physician");
  editphysiciandialog(id);

}

/*Function to Edit speciality */
function editSpeciality(id){
  reopen_dialog(520,290,"Edit Specialty");
  editspecialitydialog(id);

}

/*Function to Edit group */
function editGroup(id){
  reopen_dialog(550,180,"Edit Group");
  editgroupdialog(id);

}

/*Function to Location */
function editLocation(id, groupname){
  reopen_dialog(650,380,"Edit Location");
  editloctiondialog(id, groupname);

}

function editloctiondialog(id, groupname){
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/locationedit/'+id,
    data : 'groupname='+encodeURIComponent(groupname),
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      if($('#edit-country').val()=="US"){
        $('#usstates').show();
        $('#otherstates').hide();
      }else{
        $('#usstates').hide();
        $('#otherstates').show();
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

/*Function to view speciality physician */
function viewspecalityPhysicians(id){
  $("#dialog").dialog("destroy");
  window.location=baseurl+'physician_locator';
}

/*Function to view speciality sites */
function viewspecalitySites(id ,specialtyname){
  reopen_dialog(650,400,specialtyname+"-View Sites");
  viewspecalitySitesdialog(id);
}

/*Function to view speciality sites */
function viewwarmhandoffreports(id){
  $("#dialog").dialog("destroy");
  window.location=baseurl+'physician_locator/handoffreports';
}

/*Function to view physician */
function viewPhysician(id){
  $("#PhysicianID").val(id);
  $('#dialog').dialog('destroy');
  openDialog(viewphysiciandialog, id, 600, 385, "View Physician");
  $('#dialog').scrollTop(0);
}

function viewphysiciandialog(id){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/details/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  $('#dialog').scrollTop(0);
}

/*Function to view speciality */
function viewSpeciality(id,title){
  $("#SelectedSpecialtyID").val(id);
  $('#dialog').dialog('destroy');
  openDialog(viewspecialitydialog, id, 500, 275, title);
}

function viewpatientdetails(id)
{
  $('#dialog').dialog('destroy');
  openDialog(viewpatientdetailsdialog,id,600,300,"Patient Details");
}

function viewpatientdetailsdialog(contactid){
  var physicianid=$("#contact_physician_id").val();
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/patient_detailview/'+contactid+"/"+physicianid,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

/*Function to view group */
function viewGroup(id, title){
  $('#dialog').dialog('destroy');
  openDialog(viewgroupdialog,id,450,200,title);
}

function viewgroupdialog(id){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/groupaction/view/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Function to modify the group location
function modify_group_location (id) {
  reopen_dialog(650,400,"Search Group");
  addphysiciantoexistgroupdialog("", id);
}
				
function viewspecialitydialog(id){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/specialityaction/view/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

/*Function to check new group and exising group */
function submitGroup(){
  var specialtyid = $("#edit-specialtyid").val();
  var radioGrp = document['forms']['add-physician-group-form']['group'];
  for(i=0; i < radioGrp.length; i++){
    if (radioGrp[i].checked == true) {
      var radioValue = radioGrp[i].value;
      if(radioValue=='newgroup'){
        reopen_dialog(650,430,"Add Group");
        addgroupdialog(specialtyid);
      }else{
        reopen_dialog(650,400,"Search Group");
        addphysiciantoexistgroupdialog(specialtyid, "");
      }
    }
  }
}

function addgroupdialog(specialityid){

  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/create_group/'+specialityid,
    cache : false,
    success : function (res) {
      $('#edit-physicianid').val(editphygroupid);
      $('#dialog').html(res);
      $("#creategroup_error").hide();
      $('#group_specialityid').val(specialityid);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

/*function addphygroupdialog(phyId){
  
}*/

function addphysiciantoexistgroupdialog(specialtyid, phy_id){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/searchgroup'+(specialtyid != "" ? "/"+specialtyid : '')+(phy_id !=""?"/edit/"+phy_id:''),
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

/* function to generate report*/

function generatereport(pageno){

    
  var str = "";
  //var grouplocationid = $("#edit-grouplocationid").val();
  var spec = $("#edit-basic-specialty").val(); 
  
  var startdate = $("#edit-handoffreport-start-date").val();
  var enddate = $("#edit-handoffreport-end-date").val();

  var st = startdate.split("-");
  var et = enddate.split("-");
  var starting=st[1]+ "/"+ st[0]+"/" +st[2];
  var ending=et[1]+"/"+et[0]+"/"+et[2];
  if($.trim(startdate)=="")
    str += "From Date should not be empty";

  if($.trim(enddate)==""){
    if(str!="")
      str+= "<br/>";
    str += "To Date should not be empty";
  }
  var r= fromGreaterThanTo(starting,ending);
  if((startdate!="") && (enddate!=""))
  {
    if(!r)
    {
      str += "Start date is greater than end date";
    }
  }
  
  
  if (str != "") {
    styleStatusMessages(str, "popuperrorMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }else{ 
    $('#listingResultset').html('<div style="padding-top: 10px; padding-left:320px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $("#pagingdivtop").html("");
    $("#pagingdivbottom").html("");
    $.ajax({
      type : "POST",
      url : baseurl+'physician_locator/view_warmhandoff',      
      data : "spec="+spec+"&startdate="+startdate+"&enddate="+enddate+(pageno>1?'&page='+pageno:''),  
      //async : false,
      cache : false,
      success : function (msg) {                
        $("#listingResultset").html(msg);
        var limit = $('#hid_limit').val();
        var page = pageno;
        var counter = $('#hid_totalRec').val();
          
      
        if(counter > 0){
          var str = "";
          var to = page * limit;
          str += '<span>Showing <b>'+(counter > 0 ? (page-1) * limit+1 : 0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
          if (page > 1) {
            str += '<a href="javascript:void(0)" onclick = "generatereport('+(page-1)+')" class="red"><< Previous</a>';
          }
          if (to < counter) {
            str += ' <span class="red"> |</span><a href="javascript:void(0)" onclick = "generatereport('+(page+1)+')" class="red">Next >></a>';
          }
          $("#pagingdivtop").html(str);
          $("#pagingdivbottom").html(str);

        }


      }
    });
  }
    
}

/*Function to save group */
function saveGroup(specialtyid){
  var type = $("#edit-typevalue").val();
  var groupname = $("#edit-groupname").val();
  var grouptype = $("#edit-grouptype").val();
  var status = $("#edit-status").val();
  var country=$("#edit-country").val();
  var address1 = $("#edit-address1").val();
  var address2 = $("#edit-address2").val();

  var city = $("#edit-city").val();
  
  var state = $("#edit-state").val();
  var usstates=$("#edit-usstates").val();

  

  var zipcode = $("#edit-zipcode").val();
  var phone = $("#edit-phone").val();
  var phone1 = $("#edit-phone1").val();
  var phone2 = $("#edit-phone2").val();

  
  var phonetype = $("#edit-phonetype").val();
  var phonetype1 = $("#edit-phonetype1").val();
  var phonetype2 = $("#edit-phonetype2").val();
  var specialityId = $('#group_specialityid').val();
  var lines = 10;
  var str = "";
  
  if($.trim(groupname)=="" || $.trim(state)=="" ||$.trim(usstates)=="" ||$.trim(grouptype)=="" || $.trim(status)=="" || $.trim(address1)=="" || $.trim(city)=="" || $.trim(zipcode)=="" ||($.trim(phone)=="" && $.trim(phone1)=="" && $.trim(phone2)=="") || $.trim(country)== -1){
    if($.trim(groupname)==""){
      str += "Group name should not be empty";
      lines+=20;
    }
    if($.trim(grouptype)==""){
      if(str!="")
        str+= "<br/>";
      str += "Group type should not be empty";
      lines+=20;
    }
    if($.trim(status)==""){
      if(str!="")
        str+= "<br/>";
      str += "Status should not be empty";
      lines+=20;
    }
    
    if($.trim(country)==-1){
      if(str!="")
        str+= "<br/>";
      str += "Country should not be empty";
      lines+=20;
    }


    if($.trim(address1)==""){
      if(str!="")
        str+= "<br/>";
      str += "Address1 should not be empty";
      lines+=20;
    }

    if($.trim(city)==""){
      if(str!="")
        str+= "<br/>";
      str += "City should not be empty";
      lines+=20;
    }

    

    if(country == "US") {
      if(usstates == "")
      {
        if(str!="") str+= "<br/>";
        str += "Please select the State";
        lines+=18;
      }
    }

    if(country != "US") {
      if(state == "")
      {
        if(str!="") str+= "<br/>";
        str += "Please enter the State";
        lines+=18;
      }
    }
    
    if($.trim(zipcode)==""){
      if(str!="")
        str+= "<br/>";
      str += "Zip Code should not be empty";
      lines+=20;
    }
    
    if(($.trim(phone)=="") && ($.trim(phone1)=="") && ($.trim(phone2)=="")){
      if(str!="")
        str+= "<br/>";
      str += "Phone should not be empty";
      lines+=20;
    
    }
    if(str!=""){
      resize_dialog(650, 380+lines);
      styleStatusMessages(str, "statusMessage", "failure");
      $('#dialog').scrollTop(0);
      return;
    }
  }
  if(groupname.length > 50 || grouptype.length > 50 || address1.length > 50 || address2.length > 50 || city.length > 50 || state.length > 50 || zipcode.length > 50 || phone.length > 50 ||
    phone1.length > 50 || phone2.length > 50) {

    if (groupname.length > 50){
      if(str!="")
        str+= "<br/>";
      str += "Group name should not be more than 50 characters";
      lines+=18;
    }
    if (grouptype.length > 50){
      if(str!="")
        str+= "<br/>";
      str += "Group type should not be more than 50 characters";
      lines+=18;
    }
    if (address1.length > 50){
      if(str!="")
        str+= "<br/>";
      str += "Address1 field should not be more than 50 characters";
      lines+=18;
    }
    if($.trim(address2) != ""){
      if(address2.length >50  )
      {
        if(str!="")
          str+= "<br/>";
        str += "Address2 field should not be more than 50 characters";
        lines+=18;
      }
    }
    if (city.length > 50){
      if(str!="")
        str+= "<br/>";
      str += "City should not be more than 50 characters";
      lines+=18;
    }
    if (state.length > 50){
      if(str!="")
        str+= "<br/>";
      str += "State should not be more than 50 characters";
      lines+=18;
    }
    if (zipcode.length > 50){
      if(str!="")
        str+= "<br/>";
      str += "Zipcode should not be more than 50 characters";
      lines+=18;
    }
    if((phone.length > 50) || (phone1.length > 50) || (phone2.length > 50)){
      if(str!="")
        str+= "<br/>";
      str += "Phone number should not be more than 50 characters";
      lines+=20;

    }

    resize_dialog(650, 380+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }
  else
  {
	 
    $('#dialog').html('<div style="padding-top: 10px; padding-left: 150px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+'physician_locator/groupaction',
      data : "groupname="+encodeURIComponent(groupname)+"&grouptype="+encodeURIComponent(grouptype)+"&status="+encodeURIComponent(status)+"&country="+encodeURIComponent(country)+"&address1="+encodeURIComponent(address1)+"&usstate="+encodeURIComponent(usstates)+"&state="+encodeURIComponent(state)+"&city="+encodeURIComponent(city)+"&zipcode="+encodeURIComponent(zipcode)+"&phone1="+(phone)+"&phone2="+(phone1)+"&phone3="+(phone2)+"&phonetype1="+(phonetype)+"&phonetype2="+(phonetype1)+"&phonetype3="+(phonetype2)+"&address2="+encodeURIComponent(address2),
      async : false,
      cache : false,
      success : function (msg) {
        eval("var json="+msg);
        if(json.Message=="Success"){
          if (specialtyid == "physician"){
            select_group(json.groupId,'physician');
          }else{
            if(type=="workflow"){
              add_physician_workflow(json.groupId);
            }else{
              reopen_dialog(650,545,"Create Physician");
              createphysiciandialog(json.groupId , specialityId ,json.locationId+"||"+json.location);
            }
          }
          
        }else if(json.Message=="Failure"){
          $.ajax({
            type : "GET",
            url : baseurl+'physician_locator/create_group',
            cache : false,
            success : function (res) {
              
              $('#dialog').html(res);
              $("#edit-typevalue").val(type);
              $("#edit-groupname").val(groupname);
              $("#edit-grouptype").val(grouptype);
              $("#edit-status").val(status);
              $("#edit-address1").val(address1);
              $("#edit-address2").val(address2);
              $("#edit-city").val(city);
             
              $("#edit-zipcode").val(zipcode);
              $("#edit-country").val(country);
              $("#edit-phone").val(phone);
              $("#edit-phone1").val(phone1);
              $("#edit-phone2").val(phone2);
              $("#edit-phonetype").val(phonetype);
              $("#edit-phonetype1").val(phonetype1);
              $("#edit-phonetype2").val(phonetype2);
              $('#group_specialityid').val(specialityId);
              $("#creategroup_error").hide();

              if($.trim(country) == "US") {
                $('#usstates').show();
                $('#otherstates').hide();
                $("#edit-usstates option[value="+usstates+"]").attr("selected", "selected");
              }
              else
              {
                $('#otherstates').show();
                $('#usstates').hide();
                $("#edit-state").val(state);

              }


              styleStatusMessages("Group name already exist", "statusMessage", "failure");
            },
            error : function (res) {
              handleRequestError(res);
            }
          });
          resize_dialog(650,500+30);
        }
      }
    });
  }
}


function listusstates()
{
  // if($("#edit-find-country").val() == "United States"){
  if($("#edit-country").val() == "US"){
    $("#usstates").show();
    $("#otherstates").hide();
  }
  else{
    $("#usstates").hide();
    $("#otherstates").show();
  }
}


/*Function to save Grouplocation */
function saveGrouplocation(physicianid, groupid){
  var groupid = $("#edit-groupid").val();
  var specialtyid = $("#edit-specialtyid").val();
  var country = $("#edit-country").val();
  var usstates = $("#edit-usstates").val();
  var city = $("#edit-city").val();
  var state = $("#edit-state").val();
  var postalcode = $("#edit-postalcode").val();
  var address1 = $("#edit-address1").val();
  var address2 = $("#edit-address2").val();
  var phone1 = $("#edit-phone1").val();
  var phone2 = $("#edit-phone2").val();
  var phone3 = $("#edit-phone3").val();
  var phonetype1 = $("#edit-phonetype1").val();
  var phonetype2 = $("#edit-phonetype2").val();
  var phonetype3 = $("#edit-phonetype3").val();
  var status = $("#edit-status").val();
  var str = "";
  

  if(country == -1) {
    if(str!="") str+= "<br/>";
    str += "Please select any Country";

  }

  if($.trim(city)==""){
    if(str!="")
      str+= "<br/>";
    str += "City should not be empty";
  }
  else if(city.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "City should not be more than 50 characters";
  }

  

  if($.trim(country) == "US") {
    if(usstates == "")
    {
      if(str!="") str+= "<br/>";
      str += "Please select the State";
    }
  }
  


  if($.trim(country) != "US") {
    if($.trim(state) == "")
    {
      if(str!="") str+= "<br/>";
      str += "State Should not be empty";
    }
    else if(state.length >50)
    {
      if(str!="") str+= "<br/>";
      str += "State should not be more than 50 characters";
    }
  }
  
  if($.trim(postalcode)==""){
    if(str!="")
      str+= "<br/>";
    str += "Zip Code should not be empty";
  }
  if ($.trim(postalcode) != "") {
    postalcode = ltrim(postalcode);
    postalcode = rtrim(postalcode);
    //var re = /^[a-zA-Z0-9\s*]$/;
    var re = '[^A-Za-z0-9\\s]';
    var errstr = checkalphanumeric(postalcode,re);
    if(errstr){
      if(str!="")
        str+= "<br/>";
      //str += "Zip Code should have numerical value";
      str += errstr;
    }
  }
  
  else if(postalcode.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Postal Code should not be more than 50 characters";
  }
  if($.trim(phone1)=="" && $.trim(phone2)=="" && $.trim(phone3)==""){
    if(str!="")
      str+= "<br/>";
    str += "Phone should not be empty";
  }
  else if(phone1.length >50 || phone2.length >50 || phone3.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Phone should not be more than 50 characters";
  }
  if ($.trim(address1) == "") {
    if(str!="")
      str+= "<br/>";
    str += "Address1 should not be empty";
  }
  else if(address1.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Address1 should not be more than 50 characters";
  }
  if($.trim(address2) != ""){
    if(address2.length >50  )
    {
      if(str!="") str+= "<br/>";
      str += "Address2 should not be more than 50 characters";
    }
  }
  if(str!=""){
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }else{
    if (country == 'US'){
      state = usstates;
    }else{
      state = state;
    }
      
    $('#dialog').html('<div style="padding-top: 250px; padding-left: 350px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+'physician_locator/groupaction/grouplocation',
      data : "groupid="+encodeURIComponent(groupid)+"&city="+encodeURIComponent(city)+"&country="+encodeURIComponent(country)+"&state="+encodeURIComponent(state)+"&postalcode="+encodeURIComponent(postalcode)+"&address1="+(address1)+"&address2="+(address2)+"&phone1="+(phone1)+"&phone2="+(phone2)+"&phone3="+(phone3)+"&phonetype1="+(phonetype1)+"&phonetype2="+(phonetype2)+"&phonetype3="+(phonetype3)+"&status="+(status)+"&groupdata="+(groupid)+"&specialtyid="+(specialtyid),
      async : false,
      cache : false,
      success : function (msg) {
        eval("var json="+msg);
        if(json.Message=="Success"){
          if(physicianid && physicianid=="workflow"){
            add_physician_workflow(groupid);
          }else if(physicianid){
            reopen_dialog(650, 480, "Edit Physician");
            editphysiciandialog(physicianid, groupid);
          }else{
            reopen_dialog(650,545,"Create Physician");
            createphysiciandialog(groupid, specialtyid);
          }
        }
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  }
}

function searchGroup_name(type){
  var groupname = $("#edit-groupname").val();
  var specialtyid = $('#edit-specialityid').val();

  if ($.trim(groupname) == "") {
    styleStatusMessages("Group name should not be empty", "statusMessage", "failure");
    return false;
  }else{
    $('#statusMessage').hide();
    if(specialtyid=="edit"){
      type = "edit";
    }
    $("#group_search_result").html('<div style="padding-top: 100px; padding-left: 300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "GET",
      url : baseurl+'physician_locator/searchgroup_ajax/'+specialtyid+'/'+encodeURIComponent(groupname)+'/'+type,
      cache : false,
      success : function (res) {
        //group = Array();
        $('#group_search_result').html(res);
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
  }
  return true;
}
function enter_handle_go(event, type){
  if(event.keyCode && event.keyCode==13){
    searchGroup_name(type);
  }else if(event.which && event.which==13){
    searchGroup_name(type);
  }
}
/*Function to search Group */
function searchGroup(type){
  var specialityid  = $("#edit-specialityid").val();
  var phyid = $("#edit-physicianid").val();
  $('#dialog').html('<div style="padding-top: 100px; padding-left: 300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  reopen_dialog(650,380,"Add Group");
  if (phyid){
    editphygroupid = phyid;
    addgroupdialog(type);
  }else{
    editphygroupid = "";
    addgroupdialog(specialityid);
  }
  return false;
}

function add_group_location(groupid, physicianid){
  if(groupid=="" || groupid==undefined){
    styleStatusMessages("Please change group then add location", "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return false;
  }
  reopen_dialog(650,400,"Add Location");
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/create_group/location',
    data: "groupid="+groupid+"&physicianid="+physicianid,
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  return false;
}

function redirect_back(type){
  if(type == 'edit'){
    var physicianid = $("#edit-physicianid").val();
    reopen_dialog(650, 480, "Edit Physician");
    editphysiciandialog(physicianid);
  }
  else{
    var specId = $('#edit-specialityid').val();
    reopen_dialog(300,130,'Create Physician');
    openDialog(checkgroupdialog, specId, 300, 130, 'Create Physician');
  }
}

function checkgroup(id){
  reopen_dialog(300,130,'Create Physician');
  openDialog(checkgroupdialog, id, 300, 130, 'Create Physician');
}

function checkgroupdialog(id){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/create_physician/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}


function redirect_edit_physician(physicianid, groupid){
  if(physicianid=="workflow"){
    select_group(groupid, 'workflow');
  }else{
    reopen_dialog(650, 480, "Edit Physician");
    editphysiciandialog(physicianid, groupid);
  }
}

function redirect_physician(gid, specialtyid){
  reopen_dialog(650,545,"Create Physician");
  createphysiciandialog(gid, specialtyid);
}

function redirect_create(){
  reopen_dialog(300,130,'Create Physician');
  openDialog(checkgroupdialog,'Create Physician','create',300,130,129);
}

function redirect_search(id){
  if(id=="edit"){
    redirect_edit_physician(editphygroupid)
  }else{
    reopen_dialog(300,130, "Search group");
    checkgroupdialog(id);
  }
}

function redirect_details(id){
  reopen_dialog(600,385,"View Physician");
  //openDialog(viewphysiciandialog,id,600,385,"View Physician");
  viewphysiciandialog(id);
//$('#dialog').scrollTop(0);
}

function redirect_speciality(id, title){
  if(id=="workflow" || id==""){
    $('#dialog').dialog('destroy');
  }else{
    reopen_dialog(500,275,readCookie('specialityname'));
    openDialog(viewspecialitydialog,id,500,275,title);
  }
}


 
function select_group(gid, type){
  if(type == 'edit'){
    var physicianid = $("#edit-physicianid").val();
    reopen_dialog(650, 480, "Edit Physician");
    editphysiciandialog(physicianid, gid);
    editphygroupid = "";
  }else if(type == 'physician'){
    reopen_dialog(650, 480, "Edit Physician");
    editphysiciandialog(editphygroupid, gid);
    editphygroupid = "";
  }else if(type == 'workflow'){
    add_physician_workflow(gid);
  }else {
    var specialtyid = $("#edit-specialityid").val();
    reopen_dialog(650,545,"Create Physician");
    createphysiciandialog(gid, specialtyid);
  }
}

function createphysiciandialog(groupid ,specialtyid){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/create_physician/add/'+specialtyid+'/'+groupid,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}
//Function to check the value is available in array
function in_array(string, array) {
  for (i = 0; i < array.length; i++) {
    if($.trim(array[i]) == $.trim(string)) {
      return true;
    }
  }
  return false;
}
 
/*Function to save physician */
function submitPhysician(){
  var str = "";
  var groupid = $("#edit-groupid").val();
  var speciality = $("#edit-speciality").val();
  var firstname = $("#edit-firstname").val();
  var lastname = $("#edit-lastname").val();
  var title = $("#edit-title").val();
  var professionaltitle = $("#edit-professionaltitle").val();
  var email = $("#edit-email").val();
  var websiteurl = $("#edit-websiteurl").val();
  var status = $("#edit-status").val();
  var phone = $("#edit-phone").val();
  var phone1 = $("#edit-phone1").val();
  var phone2 = $("#edit-phone2").val();
  var phonetype = $("#edit-phonetype").val();
  var phonetype1 = $("#edit-phonetype1").val();
  var phonetype2 = $("#edit-phonetype2").val();
  var npid = $("#edit-npid").val();
  var radiogender = document.getElementsByName("gender");
  var radiogenderValue = 'M';
  for(i=0; i < radiogender.length; i++){
    if (radiogender[i].checked == true) {
      radiogenderValue = radiogender[i].value;
    }
  }
  var radioagree = $("#edit-agreed-1").get(0);
 
  var locationid = "";
  $(".location-class:checked").each( function () {
    if(locationid!="")
      locationid += ", ";
    var result = $(this).val();
    locationid =locationid+result;
  });
 
  if($.trim(firstname)==""){
    str += "Firstname should not be empty";
  }
  else if(firstname.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Firstname should not be more than 50 characters";
  }
		
  if($.trim(lastname)==""){
    if(str!="")
      str+= "<br/>";
    str += "Lastname should not be empty";
  }
  else if(lastname.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Lastname should not be more than 50 characters";
  }

  if($.trim(title)!=""){
    if(title.length >50)
    {
      if(str!="") str+= "<br/>";
      str += "Title should not be more than 50 characters";
    }
  }

  if($.trim(professionaltitle)!=""){
    if(professionaltitle.length >50)
    {
      if(str!="") str+= "<br/>";
      str += "Professional title should not be more than 50 characters";
    }
  }


  if($.trim(email)==""){
    if(str!="")
      str+= "<br/>";
    str += "Email Address should not be empty";
  }
  else if(!validateEmail((email))){
    if(str!="")
      str+= "<br/>";
    str += "Email Address not valid";
  }
  else if(email.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Email should not be more than 50 characters";
  }

  if(websiteurl != ""){
    if(!isWeburl(websiteurl)){
      if(str!="")
        str+= "<br/>";
      str += "Please enter valid site url";
    }
    else if(websiteurl.length >50)
    {
      if(str!="") str+= "<br/>";
      str += "Website URL should not be more than 50 characters";
    }
  }
  
  /*if($.trim(phone)=="" && $.trim(phone1)=="" && $.trim(phone2)==""){
    if(str!="")
      str+= "<br/>";
    str += "Phone or Mobile should not be empty";
  }
  else if(phone.length >50 || phone1.length >50 || phone2.length >50)
  {
      if(str!="") str+= "<br/>";
         str += "Phone/Fax/Mobile should not be more than 50 characters";
   }*/
  if($.trim(status)==""){
    if(str!="")
      str+= "<br/>";
    str += "Status should not be empty";
  }
  if($.trim(locationid)==""){
    if(str!="")
      str+= "<br/>";
    str += "Please choose atleast one location";
  }
  if(radioagree.checked!=true){
    if(str!="")
      str+= "<br/>";
    str += "Please choose Physician Consent";
  }
  if (str != "") {
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }else{
    $('#dialog').html('<div style="padding-top: 200px; padding-left: 300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+'physician_locator/create',
      data : "firstname="+(firstname)+"&lastname="+(lastname)+"&title="+encodeURIComponent(title)+"&professionaltitle="+encodeURIComponent(professionaltitle)+"&email="+encodeURIComponent(email)+"&websiteurl="+encodeURIComponent(websiteurl)+"&status="+(status)+"&phone="+(phone)+"&phone="+(phone1)+"&phone="+(phone2)+"&phonetype="+(phonetype)+"&phonetype1="+(phonetype1)+"&phonetype="+(phonetype2)+"&locationid="+(locationid)+"&speciality="+(speciality)+"&gender="+(radiogenderValue)+"&npid="+(npid)+"&groupid="+groupid,
      async : false,
      cache : false,
      success : function (msg) {
        if(msg=='Success'){
          $("#dialog").dialog("destroy");
          openAlertDialog(300,130,"Information", "A New physician is added successfully", "success");
        }
        else{
          $("#dialog").dialog("destroy");
          openAlertDialog(250,130,"Error", "Failure to add physician", "information");
        }
      }
    });
  }
}

/*Function to editsave physician */
function editsavePhysician(){
  var str = "";
  var groupid = $("#edit-groupid").val();
  var physicianid = $("#edit-physicianid").val();
  var speciality = "";
  var firstname = $("#edit-firstname").val();
  var lastname = $("#edit-lastname").val();
  var title = $("#edit-title").val();
  var professionaltitle = $("#edit-professionalTitle").val();
  var email = $("#edit-email").val();
  var websiteurl = $.trim($("#edit-websiteurl").val());
  var status = $("#edit-status").val();
  var npid = $("#edit-NPID").val();
  var gender = 'M';
  var radiogender = document.getElementsByName("gender");
  for(i=0; i < radiogender.length; i++){
    if (radiogender[i].checked == true) {
      gender = radiogender[i].value;
    }
  }
  
  var locationid = "";
  $(".location-class:checked").each( function () {
    if(locationid!="")
      locationid += ", ";
    var result = $(this).val();
    locationid = locationid+result;
  });

  if($.trim(firstname)==""){
    str += "Firstname should not be empty";
  }
  else if(firstname.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Firstname should not be more than 50 characters";
  }
		
  if($.trim(lastname)==""){
    if(str!="")
      str+= "<br/>";
    str += "Lastname should not be empty";
  }
  else if(lastname.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Lastname should not be more than 50 characters";
  }
  if($.trim(title)!=""){
    if(title.length >50)
    {
      if(str!="") str+= "<br/>";
      str += "Title should not be more than 50 characters";
    }
  }
  if($.trim(professionaltitle)!=""){
    if(professionaltitle.length >50)
    {
      if(str!="") str+= "<br/>";
      str += "Professional title should not be more than 50 characters";
    }
  }
   
  if($.trim(email)==""){
    if(str!="")
      str+= "<br/>";
    str += "Email Address should not be empty";
  }
  else if(!validateEmail((email))){
    if(str!="")
      str+= "<br/>";
    str += "Email Address not valid";
  }
  else if(email.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Email should not be more than 50 characters";
  }
  if(websiteurl != ""){
    if(!isWeburl(websiteurl)){
      if(str!="")
        str+= "<br/>";
      str += "Please enter valid site url";
    }
    else if(websiteurl.length >50)
    {
      if(str!="") str+= "<br/>";
      str += "Website URL should not be more than 50 characters";
    }
  }
  if(status == 0){
    if(str!="")
      str+= "<br/>";
    str += "Please choose any status";
  }
  if(locationid == ""){
    if(str!="")
      str+= "<br/>";
    str += "Please choose any one location";
  }
  var spname="";
  var obj = $("#edit-speciality").get(0);
  for(var i=0;i<obj.options.length;i++){
    if(spname!=""){
      spname+="$$^^$$";
    }
    spname+= obj.options[i].text;
    if (speciality != ""){
      speciality += ",";
    }
    speciality += obj.options[i].value;
  }
  if(speciality==""){
    if(str!="")
      str+= "<br/>";
    str += "Please choose atleast one specialty";
  }
  if (str != "") {
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }
  
  $('#dialog').html('<div style="padding-top: 150px; padding-left: 270px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/actions/edit',
    data : "physicianid="+(physicianid)+"&firstname="+(firstname)+"&lastname="+(lastname)+"&title="+encodeURIComponent(title)+"&email="+encodeURIComponent(email)+"&websiteurl="+encodeURIComponent(websiteurl)+"&gender="+encodeURIComponent(gender)+"&status="+(status)+"&npid="+(npid)+"&speciality="+speciality+"&gp_loc_ids="+locationid+"&groupid="+groupid+"&spl_name="+encodeURIComponent(spname),
    async : false,
    cache : false,
    success : function (msg) {
      if(msg=="Success"){
        openAlertDialog(300, 130, "Information", "Physician details updated successfully", "success");
        $("#dialog").dialog("destroy");        
        var pageno = $("#hid_pageno").val();
        applyphysicianAction(pageno,"physician");
      }else{
        $("#dialog").dialog("destroy");
        openAlertDialog(300, 130, "Error", "Error in editing physician", "information");
      }
    }
  });
}

/*Function to editsave physician */
function editsaveLocation(){
  var str = "";
	
  var grouplocationid   = $("#edit-grouplocationid").val();
  var city              = $("#edit-city").val();
  var country           = $("#edit-country").val();
  var usstates          =  $('#edit-usstates').val();
  var state             = $("#edit-state").val();
  var postalcode        = $("#edit-postalcode").val();
  var status            = $("#edit-status").val();
  var address1          = $("#edit-address1").val();
  var address2          = $("#edit-address2").val();
  var phone1            = $("#edit-phone1").val();
  var phone2            = $("#edit-phone2").val();
  var phone3            = $("#edit-phone3").val();
  var phonetype1        = $("#edit-phonetype1").val();
  var phonetype2        = $("#edit-phonetype2").val();
  var phonetype3        = $("#edit-phonetype3").val();
  
  var lines=0;
  var str1="";
  var lines1=0;
  
  
  
																																																			
																																																							 
																																																							 
																																																							 
  if($.trim(city)=="" || $.trim(state)=="" || $.trim(usstates)==""  || ($.trim(postalcode)== "" || isNaN(postalcode)) || $.trim(address1)=="" || ($.trim(phone1)=="" && $.trim(phone2)=="" && $.trim(phone3)=="" || $.trim(country)== -1))
  {
    
	
	
    if(country == -1) {
      if(str!="") str+= "<br/>";
      str += "Please select any Country";
      lines+=18;
    }
   
    if($.trim(address1)==""){
      if(str!="")
        str+= "<br/>";
      str += "Address1 should not be empty";
      lines+=20;
    }
	
	
    if($.trim(city)==""){
      str+= "<br/>";
      str += "City should not be empty";
      lines+=20;
    }
   
   

    if($.trim(country) == "US") {
      if(usstates == "")
      {
        if(str!="") str+= "<br/>";
        str += "Please select the State";
        lines+=18;
      }
    }


    if($.trim(country) != "US") {
      if($.trim(state) == "")
      {
        if(str!="") str+= "<br/>";
        str += "State should not be empty";
        lines+=18;
      }
    }
	
	
    if($.trim(postalcode)==""){
      if(str!="")
        str+= "<br/>";
      str += "Zip Code should not be empty";
      lines+=20;
    }
	
	
    if ($.trim(postalcode) != "") {
      postalcode = ltrim(postalcode);
      postalcode = rtrim(postalcode);
      var re = '[^A-Za-z0-9\\s]';
      var errstr = checkalphanumeric(postalcode,re);
      if(errstr){
        if(str!="")
          str+= "<br/>";
        //str += "Zip Code should have numerical value";
        str += errstr;
        lines+=20;
      }
    }
	
	
    if($.trim(phone1)== "" && $.trim(phone2)=="" && $.trim(phone3)=="" ){
      if(str!="")
        str+= "<br/>";
      str += "Phone should not be empty";
      lines+=20;
    }
	
  
	
    
    
  }
   
  if($.trim(city)!="" || $.trim(state)!="" || $.trim(usstates)!="" ||$.trim(address2)!=""  || ($.trim(postalcode)!= "" || isNaN(postalcode)) || $.trim(address1)!="" || ($.trim(phone1)!="" && $.trim(phone2)!="" && $.trim(phone3)!="" || $.trim(country)!= -1))
  {
    if ($.trim(address1) != "")
    {
      if(address1.length >50)
      {
        if(str!="") str+= "<br/>";
        str += "Address1 should not be more than 50 characters";
        lines+=18;

      }
    }

    if ($.trim(address2) != "")
    {
      if(address2.length >50)
      {
        if(str!="") str+= "<br/>";
        str += "Address2 should not be more than 50 characters";
        lines+=18;

      }
    }

    if ($.trim(city) != "")
    {
      if(city.length >50)
      {
        if(str!="") str+= "<br/>";
        str += "City should not be more than 50 characters";
        lines+=18;

      }
    }

    if ($.trim(state) != "")
    {
      if(state.length >50)
      {
        if(str!="") str+= "<br/>";
        str += "State should not be more than 50 characters";
        lines+=18;

      }
    }

    if ($.trim(usstates) != "")
    {
      if(usstates.length >50)
      {
        if(str!="") str+= "<br/>";
        str += "State should not be more than 50 characters";
        lines+=18;

      }
    }

    if ($.trim(postalcode) != "")
    {
      if(postalcode.length >50)
      {
        if(str!="") str+= "<br/>";
        str += "Zip code should not be more than 50 characters";
        lines+=18;

      }
    }

    if ($.trim(phone1) != "")
    {
      if(phone1.length >50)
      {
        if(str!="") str+= "<br/>";
        str += "Phone1 should not be more than 50 characters";
        lines+=18;

      }
    }

    if ($.trim(phone2) != "")
    {
      if(phone2.length >50)
      {
        if(str!="") str+= "<br/>";
        str += "Phone2 should not be more than 50 characters";
        lines+=18;

      }
    }

    if ($.trim(phone3) != "")
    {
      if(phone3.length >50)
      {
        if(str!="") str+= "<br/>";
        str += "Phone3 should not be more than 50 characters";
        lines+=18;

      }
    }
    
           
  }
  
  if(str != "")
  {
    resize_dialog(650, 380+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }


  else{
    if (country == "US"){
      state = usstates;
    }else{
      state = state;
    }
    $('#dialog').html('<div style="padding-top: 10px; padding-left: 150px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+'physician_locator/locationactions/edit',
      data : "grouplocationid="+(grouplocationid)+"&country="+(country)+"&city="+(city)+"&state="+(state)+"&postalcode="+encodeURIComponent(postalcode)+"&address1="+encodeURIComponent(address1)+"&address2="+encodeURIComponent(address2)+"&phone1="+(phone1)+"&phonetype1="+(phonetype1)+"&phone2="+(phone2)+"&phonetype2="+(phonetype2)+"&phone3="+(phone3)+"&phonetype3="+(phonetype3)+"&status="+(status),
      async : false,
      cache : false,
      success : function (msg) {
        $("#dialog").dialog("destroy");
        openAlertDialog(300, 130, "Success", "Location details updated successfully", "success");
      //$("#listingResultset").html(msg);
      //thisPage = location.href.substring((location.href.lastIndexOf("/"))+1)
      //location.href=document.location;
    		 
      //create pagination links through AJAX
      //create_pagination_links(counter, page, limit, locate, 'applySubjectsFilterAction');
			
      }
    });
  }
   
}

function checkalphanumeric(strval,strRegExp)
{
   var ret="";
    var charpos = strval.search(strRegExp);
    if(strval.length > 0 &&  charpos >= 0)
    {
      ret = "Zipcode should have alphanumeric value only";
    }//if 
   return ret;
}


function ltrim(str) {
  return str.replace(/^\s+/,"");
}
function rtrim(str) {
  return str.replace(/\s+$/,"");
}

/*Function to activate and deactivate physician */
function activatephysician(id,status){
	
  if(status=="Active"){
    status = "Inactive";
    confirmMsg = "deactivate";
    succActmsg = "deactivated";
  }else{
    status = "Active";
    confirmMsg = "activate";
    succActmsg = "activated";
  }
 

  openConfirmBox(function(){
    $("#alertdialog").dialog("destroy");
    $('#dialog').html('<div style="padding-top:100px; padding-left:220px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+"physician_locator/actions/activate/"+id,
      data: "status="+status,
      async : false,
      cache : false,
      success : function (msg) {
        if(msg=="success"){
          openAlertDialog(300, 130, "Success", "Selected physician "+succActmsg+" successfully", "success");
          $('#physician_status_'+id).html(status);
          reopen_dialog(600,385,"View Physician");
          $('#dialog').scrollTop(0);
          viewphysiciandialog(id);
        }
      }
    });
  
  },300,130,"Confirm "+confirmMsg,"Do you want to "+confirmMsg+"?");
}

/*Function to activate and deactivate specialitydialog */
function activatespecialitydialog(id,status){
 
  if(status=="Active"){
    status = "Inactive";
    openConfirmBox(function(){
    
      activatespeciality(id,status);
    
    },300,130,"Confirm Deactivate","Do you want to deactivate?");
  }
  else{
    status = "Active";
    openConfirmBox(function(){
      activatespeciality(id,status);
    },300,130,"Confirm Activate","Do you want to activate?");
  }
}

/*Function to activate and deactivate speciality */
function activatespeciality(id,status){
  
  $("#alertdialog").dialog("destroy");
  $('#dialog').html('<div style="padding-top:100px; padding-left:220px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');

  $.ajax({
    type : "POST",
    url : baseurl+"physician_locator/specialityactions/activate/"+id,
    data: "status="+status,
    async : true,
    cache : false,
    success : function (msg) {
      if(msg=="Success"){
        $("#dialog").dialog("destroy");
        if (status == "Active"){
          errActivemsg = "activated";
        }
        else{
          errActivemsg = "deactivated";
        }
        openAlertDialog(300, 130, "Success", "Selected specialties "+errActivemsg+" successfully", "success");
        $('#speciality_statusCode'+id).html("<p>"+status+"</p>");
      }
    }
  });
}

/*Function to activate and deactivate speciality */
function activategroup(id,status){
	
  if(status=="Active"){
    status = "Inactive";
    confgroupMsg = "deactivate";
    succgroupmsg = "deactivated";
  }else{
    status = "Active";
    confgroupMsg = "activate";
    succgroupmsg = "activated";
  }
  openConfirmBox(function(){
    $("#alertdialog").dialog("destroy");
    $('#dialog').html('<div style="padding-top:30px; padding-left:200px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+"physician_locator/groupactions/activate/"+id,
      data: "status="+status,
      async : false,
      cache : false,
      success : function (msg) {
        if(msg=="Success"){
          openAlertDialog(350, 140, "Success", "Selected group "+succgroupmsg+" successfully", "success");
          reopen_dialog(450,180,"View Group");
          $('#group_statusCode'+id).html("<p>"+status+"</p>");
          viewgroupdialog(id);
         

        }
      }
    });
  },300,130,"Confirm "+confgroupMsg,"Do you want to "+confgroupMsg+"?");
}

/*Function to save speciality */
function submitSpeciality(){
  var specialityname = $.trim($('#edit-specialityname').val());
  var status = $('#edit-status').val();
  var desc = $('#edit-specialitydesc').val();
  var allow = $('#edit-check-invite').get(0).checked;
  if (allow){
    allowbool = "true";
  }else{
    allowbool = "false";
  }
 
  var str = "";
  //code to validate the fields
  var lines = 10;
  if (specialityname == "") {
    str += "Please enter the Specialty Name";
    lines+=18;
  }
  if (specialityname != "") {
    if(specialityname.length > 50) {
      if(str!="")
        str+= "<br/>";
      str += "Specialty should not be more than 50 characters";
      lines+=18;
    }
  }
  if (str != "") {
    resize_dialog(520,290+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    return;
  }
  
  $('#dialog').html('<div style="padding-top: 90px; padding-left: 240px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/specialityaction',
    data : "specialityname="+encodeURIComponent(specialityname)+"&status="+encodeURIComponent(status)+"&desc="+encodeURIComponent(desc)+"&allow="+allowbool,
    async : false,
    cache : false,
    success : function (msg) {
      msg = $.trim(msg);
      if(msg=="AddCreateria"){
        reopen_dialog(650,490,"Criteria To Confirm Qualification");
        criteriaDialog(0);
      }else if(msg=="Success"){
        if ($("#module").val() == "Speciality") {
          var pageno = $('#hid_pageno').val();
          $("#dialog").dialog("destroy");
          openAlertDialog(300, 130, "Success", "Specialty added successfully", "success");
          applyspecialityAction(pageno, 'view_speciality');
        }
      }else if(msg=="Specialty name already exist"){
        $.ajax({
          type : "GET",
          url : baseurl+'physician_locator/create_speciality',
          cache : false,
          success : function (res) {
            $('#dialog').html(res);
            $('#edit-specialityname').val(specialityname);
            $('#edit-status').val(status);
            $('#edit-specialitydesc').val(desc);
            if(allow){
              $('#edit-check-invite').get(0).checked = true;

              $('#spec_create').show();
              $('#spec_create_createris').hide();
               
            }else{
              $('#edit-check-invite').get(0).checked = false;
              $('#spec_create_createris').show();
              $('#spec_create').hide();
            }

            resize_dialog(520,290+30);
            styleStatusMessages("Specialty name already exist", "statusMessage", "failure");
          },
          error : function (res) {
            handleRequestError(res);
          }
        });
      }else{
        $('#dialog').dialog('destroy');
        openAlertDialog(300, 130, "Error", msg, "Error");
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
    
  });
}

function criteriaDialog(id){
  $.ajax({
    type : "GET",
    url  : baseurl+'physician_locator/add_criteria/'+id,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

/*Function to edit save speciality */
function editsaveSpeciality(){
  var specialityid = $('#edit-specialityid').val();
  var specialityname = $('#edit-specialityname').val();
  var specialitydesc = $('#edit-specialitydesc').val();
  var allow = $('#edit-invite').get(0).checked;
  var status = $('#edit-status').val();
  var str = "";
  var lines = 0;
  if($.trim(specialityname)== "" || $.trim(status)=="" || status=="0"){
    if($.trim(specialityname)==""){
      str += "Please enter the Specialty Name";
      lines+=20;
    }
   
    if(status=="0"){
      if(str!="")
        str+= "<br/>";
      str += "Status should not be empty";
      lines+=20;
    }
    resize_dialog(520, 290+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }else   
  if(specialityname.length > 50) {
    if(str!="")
      str+= "<br/>";
    str += "Specialty should not be more than 50 characters";
    lines+=18;
    resize_dialog(520, 290+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }
   
        
  
 

  else{
    var pageno   = $('#hid_pageno').val();
    $("#pagingdivtop").html('');
    $("#pagingdivbottom").html('');
    $.ajax({
      type : "POST",
      url : baseurl+'physician_locator/specialityactions/edit',
      data : "specialityid="+(specialityid)+"&specialityname="+encodeURIComponent(specialityname)+"&status="+encodeURIComponent(status)+"&desc="+encodeURIComponent(specialitydesc)+"&allow="+allow,
      async : false,
      cache : false,
      success : function (msg) {
        if(msg=="Success"){
          $("#listingResultset").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
          $("#dialog").dialog("destroy");
          openAlertDialog(300, 130, "Success", "Specialty updated successfully", "success");
          applyAction(pageno,'view_speciality');
        }else if(msg=="Specialty Name Not Unique"){
          resize_dialog(520, 290+30);
          styleStatusMessages("Specialty name already exist", "statusMessage", "failure");
          $('#dialog').scrollTop(0);
        }
      }
    });
		
  }
}

function assignspecialty(id){
  openDialog(assignspecialitydialog,'', 650, 430, 'Assign Specialty to site');
}

function assignspecialitydialog(siteid){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/assign_speciality/'+siteid,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function editphysiciandialog(id, groupid){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/edit/'+id+(groupid?'/'+groupid:''),
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

/*Function to edit save group */
function editsaveGroup(){
  var groupid = $('#edit-groupid').val();
  var groupname = $('#edit-groupname').val();
  var grouptype = $('#edit-grouptype').val();
  var status = $('#edit-status').val();
  var str = "";
  var lines = 0;
  if($.trim(groupname)=="" || $.trim(status)=="" || $.trim(status)==0 || $.trim(grouptype)==""){
    if($.trim(groupname)==""){
      str += "Group name should not be empty";
      lines+=20;
    }
    if($.trim(status)=="" || $.trim(status)==0){
      if(str!="")
        str+= "<br/>";
      str += "Status should be selected";
      lines+=20;
    }
    if($.trim(grouptype)==""){
      if(str!="")
        str+= "<br/>";
      str += "Group type should not be empty";
      lines+=20;
    }
    resize_dialog(550, 180+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }else if(groupname.length > 50 || grouptype.length > 50) {

    if (groupname.length > 50){
      if(str!="")
        str+= "<br/>";
      str += "Group name should not be more than 50 characters";
      lines+=20;
    }
    if (grouptype.length > 50){
      if(str!="")
        str+= "<br/>";
      str += "Group type should not be more than 50 characters";
      lines+=20;
    }

    resize_dialog(550, 180+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }

  else{
    $('#dialog').html('<div style="padding-top: 10px; padding-left: 150px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+'physician_locator/groupactions/edit',
      data : "groupid="+(groupid)+"&groupname="+encodeURIComponent(groupname)+"&grouptype="+encodeURIComponent(grouptype)+"&status="+encodeURIComponent(status),
      async : false,
      cache : false,
      success : function (msg) {
       
        if (msg == "Success"){
          $("#dialog").dialog("destroy");
          openAlertDialog(300, 130, 'Success', 'Group Name Updated successfully', 'success');
          location.href=document.location;
        }
        if (msg =="Group name already exist"){
          $.ajax({
            type : "GET",
            url : baseurl+'physician_locator/groupedit/'+groupid,
            cache : false,
            success : function (res) {
              $('#dialog').html(res);
              styleStatusMessages('Group Name already exists!', "statusMessage", "failure");
              $('#dialog').scrollTop(0);
            },
            error : function (res) {
              handleRequestError(res);
            }
          });
             
        //$("#dialog").dialog("destroy");
        // openAlertDialog(300, 130, "Error", "Group Name Already exists!", "Error");
        }
      }
    });
		
  }
}

function selectedAssignspeciality(){
  var selectedobj = document.getElementById('edit-site');
  var selectedindex = selectedobj.selectedIndex;
  siteid = selectedobj.options[selectedindex].value;
	
  reopen_dialog(650,430,"Assign Specialty to site");
  assignspecialitydialog(siteid);
}

function getspecialitydetails()
{
 
  var specid=$('#edit-notification-speciality').val();
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/getspeciality_templatedetails/'+specid,
    cache : false,
    success : function (res) {
      eval('var json='+res);
      $('#edit-warmhandoff-from-name').val(json.Name);
      $('#edit-warmhandoff-from-email').val(json.From);
      $('#edit-warmhandoff-reply-to').val(json.Recipient);
      $('#edit-warmhandoff-subject').val(json.Subject);
      if(json.Message == "")json.Message="No Notification";
      editor.setData(json.Message);
      
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
 
 
}



/*Function to Assign speciality  to site*/
function submitAssignspeciality(){

  var siteid = $('#edit-site').val();
  var selObj = $('#edit-destspeclity').get(0);
  
  var selectedspeclity = "";
  for(var i=0;i<selObj.options.length;i++){
    if(selectedspeclity!="")
      selectedspeclity +=",";
    selectedspeclity += selObj.options[i].value;
  }
  
  var str = "";
  var lines = 0;
  if($.trim(siteid)=="" || $.trim(selectedspeclity)=="" || $.trim(siteid)==0){
    if($.trim(siteid)==0){
      if(str!="")
        str+= "<br/>";
      str += "Please select a site";
      lines += 25;
    }
    if($.trim(selectedspeclity)==""){
      if(str!="")
        str+= "<br/>";
      str += "Please assign atleast one specialty to a site";
      lines += 25;
    }
    resize_dialog(650, 430+lines);
    styleStatusMessages(str, "statusMessage", "failure");
    //$('#dialog').scrollTop(0);
    return;
  }else{
		
    $('#dialog').html('<div style="padding-top: 180px; padding-left: 300px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+'physician_locator/specialityaction/assign',
      data : "siteid="+siteid+"&speciality="+encodeURIComponent(selectedspeclity),
      async : false,
      cache : false,
      success : function (msg) {
        $("#dialog").dialog("destroy");
        openAlertDialog(300, 130, "Success", "Specialties updated successfully", "success");
        var myStr = document.location;
        var strLen = myStr.Length;
        myStr = myStr.replace('', '#');
        $("#listingResultset").html('<div style="padding-top: 50px; padding-left: 330px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
        window.location = document.location;
      }
    });
		
  }
}


function proceedspeciality()
{
  var handoffspecialities=$("#handoff-specialities").val();
  var str="";
  if($.trim(handoffspecialities)== "-1"){
    if(str!="")
      str+= "<br/>";
    str += "Specialty Name should not be empty";
    styleStatusMessages(str, "statusMessage", "failure");
  }
  
  if($.trim(handoffspecialities)!= "-1")
  {
    window.location=baseurl+'physician_locator/handoffreports/'+handoffspecialities;
  }
  
}






/*function for list box add item  */

function listbox_moveacross(sourceID, destID) {
  var src = document.getElementById(sourceID);
  var dest = document.getElementById(destID);
 
  
  var isSelected = false;
  for(var count=0; count < src.options.length; count++) {
    if(src.options[count].selected == true) {
      isSelected = true;
      for(var i=0; i<dest.options.length; i++) {
        if(dest.options[i].value == 0) {
          dest.remove(0);
        }
      }
      var option = src.options[count];
      var newOption = document.createElement("option");
      if (option.value !=0){
        newOption.value = option.value;
        newOption.text = option.text;
      
        newOption.selected = true;
        try {
          dest.add(newOption, null); //Standard
          src.remove(count, null);
        }catch(error) {
          dest.add(newOption); // IE only
          src.remove(count);
        }
        count--;
        99054
      }else{
        isSelected=false;
      }
    }
  }
  if(isSelected==false){
    openAlertDialog(300, 130, "Information", "Please select atleast one specialty", "information");
  }
  
    
}

function listbox_moveall(sourceID, destID) {
  var src = document.getElementById(sourceID);
  var dest = document.getElementById(destID);
  
  for(var count=0; count < src.options.length; count++) {
    for(var i=0; i<dest.options.length; i++) {
      if(dest.options[i].value == 0) {
        dest.remove(0);

      }
    }
    var option = src.options[count];
    var newOption = document.createElement("option");
    if (option.value !=0){
      newOption.value = option.value;
      newOption.text = option.text;
      newOption.selected = true;
      try {
        dest.add(newOption, null); //Standard
        src.remove(count, null);
     
      }catch(error) {
        dest.add(newOption); // IE only
        src.remove(count);
      }
      count--;
    }
  }
}

/*function for list box add item  ends here */
function filterdata_physician_locator(){
  var search_fname = $('#edit-locator-search-firstname').val();
  var search_lname = $('#edit-locator-search-lastname').val();
  var search_email = $('#edit-locator-search-email').val();
  var search_npid = $('#edit-locator-search-npid').val();
  var search_status = $('#edit-locator-search-status').val();
  
  var data = "";
  if($.trim(search_fname)!=""){
    data+="&search_firstname="+search_fname;
  }
  if($.trim(search_lname)!=""){
    data+="&search_lastname="+search_lname;
  }
  if($.trim(search_email)!=""){
    data+="&search_email="+search_email;
  }
  if($.trim(search_npid)!=""){
    data+="&search_npid="+search_npid;
  }
  if($.trim(search_status)!="ANY"){
    data+="&search_status="+search_status;
  }
  return data;
}
function filterdata_view_speciality(){
  var search_sname = $('#edit-speciality-search-specialityname').val();
  var search_status = $('#edit-speciality-search-status').val();
  var search_date = $('#edit-speciality-search-date').val();
  var data = "";
  if($.trim(search_sname)!=""){
    data+="&search_specialityname="+search_sname;
  }
  if($.trim(search_status)!="" && $.trim(search_status)!="ANY"){
    data+="&search_status="+search_status;
  }
  if($.trim(search_date)!=""){
    data+="&search_date="+search_date;
  }
  return data;
}


function filterdata_view_group(){
  var search_gname = $('#edit-group-search-groupname').val();
  var search_gtype = $('#edit-group-search-grouptype').val();
  var search_status = $('#edit-group-search-status').val();
  var data = "";
  if($.trim(search_gname)!=""){
    data+="&search_groupname="+search_gname;
  }
  if($.trim(search_status)!="" && $.trim(search_status)!="ANY"){
    data+="&search_status="+search_status;
  }
  if($.trim(search_gtype)!=""){
    data+="&search_grouptype="+search_gtype;
  }
  return data;
}
function filterdata_view_invites(){
  var search_inviteename = $('#edit-invite-search-inviteename').val();
  var search_invitername = $('#edit-invite-search-invitename').val();
  var search_groupname = $('#edit-invite-search-groupname').val();
  var search_status = $('#edit-invite-search-status').val();
  var search_date=$('#edit-invite-search-date').val();
  var data = "";

  if($.trim(search_inviteename)!=""){
    data+="&search_inviteename="+search_inviteename;
  }
  if($.trim(search_invitername)!=""){

    data+="&search_invitename="+search_invitername;
  }
  if($.trim(search_groupname)!=""){

    data+="&search_groupname="+search_groupname;
  }
  if($.trim(search_status)!=""){

    data+="&search_status="+search_status;
  }
  if($.trim(search_date)!=""){

    data+="&search_date="+search_date;
  }
  
  return data;
}

function filterdata_view_warmhandoff(){
  
  
  var data = "";
  var stdate=$('#edit-handoffreport-start-date').val();
  var eddate=$('#edit-handoffreport-end-date').val();
  var spec=$('#edit-basic-specialty').val();
 
  if (stdate == '')
  {
    /*  var dt= new Date();
    var my_date= dt.getDate();
    var my_month=dt.getMonth()+1;
    var monlen=my_month.toLocaleString();
    var len=monlen.length;
    if(len == 1)
    my_month="0"+my_month;
    var my_year=dt.getFullYear();
    var startdate= my_month+"-"+my_date+"-"+my_year;*/
    var startdate ="";
     
  }
  else
  {
    var startdate= $('#edit-handoffreport-start-date').val();
  }

  if (eddate == '')
  {
    /* var dt= new Date();
    var my_date= dt.getDate();
    var my_month=dt.getMonth()+1;
    var monlen=my_month.toLocaleString();
    var len=monlen.length;
    if(len == 1)
    my_month="0"+my_month;
    var my_year=dt.getFullYear();
    var enddate= my_month+"-"+my_date+"-"+my_year;*/
    var enddate="";

  }
  else
  {
    var enddate=$('#edit-handoffreport-end-date').val();
  }
      
  
  data+="&startdate="+startdate;
  data+="&enddate="+enddate;
  data+="&spec="+spec;
  return data;
}

//Function to check the value is available in array
function in_array(string, array) {
  for (i = 0; i < array.length; i++) {
    if(array[i] == string) {
      return true;
    }
  }
  return false;
}


//Function to add group ID
var group = new Array();
var group_ids = new Array();
var loc_id_name = new Array();
function add_group_id (lid, gid, lname) {
  var id_name = lid+"||"+lname;
  //store the location id
  
  if (in_array(lid, group)) {
    for (i in group) {
      if (group[i] == lid) {
        group.splice(i, 1);
      }
    }
  }
  else {
    group.push(lid);
  }

  var gps = group.join(",");
  $("#edit-groupid").val(gps);

  //store the group id
  if (in_array(gid, group_ids)) {
    for (i in group_ids) {
      if (group_ids[i] == gid && group[i] == lid) {
        //if (group_ids[i] == gid ) {
        group_ids.splice(i, 1);
      }
    }
  }
  else {
    group_ids.push(gid);
  }

  var grp_ids = group_ids.join(",");
  $("#edit-groupid-store").val(grp_ids);
  //store the group id
  if (in_array(id_name, loc_id_name)) {
    for (i in loc_id_name) {
      if (loc_id_name[i] == id_name) {
        loc_id_name.splice(i, 1);
      }
    }
  }
  else {
    loc_id_name.push(id_name);
  }

  var hid_id_name = loc_id_name.join(",");
  $("#edit-location-id-name").val(hid_id_name);
}

/*
   * For Physician Updater
   **/

function physician_search(){
  openDialog(physician_search_dialog, 0, 500, 300, "Search Physician");
  return false;
}
function redo_search(){
  $('#dialog').html('<div style="padding-top: 90px; padding-left: 200px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  resize_dialog(500, 300);
  openDialog(physician_search_dialog,0,500,300,"Search Physician");
  return false;
}
function physician_search_dialog(){
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/search',
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });

}

function sel_group_workflow(){
  reopen_dialog(300, 130, "Select group");
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/create_physician/workflow',
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function addlocation_workflow(){
  var groupid   = $("#edit-groupid").val();
  var firstname   = $("#edit-firstname").val();
  var lastname    = $("#edit-lastname").val();
  var title       = $("#edit-title").val();
  var professionaltitle = $("#edit-professionaltitle").val();
  var email      = $("#edit-email").val();
  var websiteurl = $("#edit-websiteurl").val();
  var npid       = $("#edit-npid").val();
  var phone      = $("#edit-phone").val();
  var phonetype  = $("#edit-phonetype").val();
  var phone1      = $("#edit-phone1").val();
  var phonetype1  = $("#edit-phonetype1").val();
  var phone2      = $("#edit-phone2").val();
  var phonetype2  = $("#edit-phonetype2").val();
  var status     = $("#edit-status").val();
  var radiogender = document.getElementsByName("gender");

  websiteurl = websiteurl.replace(new RegExp(/^http\:\/\/|^https\:\/\/|^ftp\:\/\//i),"");
  var radiogenderValue = 'M';
  for(i=0; i < radiogender.length; i++){
    if (radiogender[i].checked == true) {
      radiogenderValue = radiogender[i].value;
    }
  }
  
  var locationid = "";
  $(".location-class:checked").each( function () {
    if(locationid!="")
      locationid += ",";
    var result = $(this).val();
    locationid =locationid+result;
  });

  var physicianformdata = '{"firstname":"'+firstname+'","lastname":"'+lastname+'","title":"'+title+'","proftitle":"'+professionaltitle+'","email":"'+email+'","websiteurl":"'+ websiteurl+'","npid":"'+npid+'","phone":"'+phone+'","phonetype":"'+phonetype+'","phone1":"'+phone1+'","phonetype1":"'+phonetype1+'","phone2":"'+phone2+'","phonetype2":"'+phonetype2+'","gender":"'+radiogenderValue+'","status":"'+status+'","locations":"'+locationid+'"}';

  reopen_dialog(650,400,"Add Location");
  addlocationdialog(groupid , 'workflow', physicianformdata);
}

function add_physician_workflow(gid){
  reopen_dialog(580,500,"Create Physician");
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/create_workflow/'+gid,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

/*Function to save physician */
function submitPhysician_workflow(){
  var str = "";
  var groupid = $('#edit-groupid').val();
  var firstname = $("#edit-firstname").val();
  var lastname = $("#edit-lastname").val();
  var title = $("#edit-title").val();
  var professionaltitle = $("#edit-professionaltitle").val();
  var email = $("#edit-email").val();
  var websiteurl = $("#edit-websiteurl").val();
  var npid = $("#edit-npid").val();
  var phone = $("#edit-phone").val();
  var phone1 = $("#edit-phone1").val();
  var phone2 = $("#edit-phone2").val();
  var phonetype = $("#edit-phonetype").val();
  var phonetype1 = $("#edit-phonetype1").val();
  var phonetype2 = $("#edit-phonetype2").val();
  //var speciality = $("#edit-speciality").val();
  
  var radiogender = document.getElementsByName("gender");
  var radiogenderValue = 'M';
  for(i=0; i < radiogender.length; i++){
    if (radiogender[i].checked == true) {
      radiogenderValue = radiogender[i].value;
    }
  }

  var locationid = "";
  $(".location-class:checked").each( function () {
    if(locationid!="")
      locationid += ", ";
    var result = $(this).val();
    locationid =locationid+result;
  });

  if($.trim(firstname)==""){
    str += "Firstname should not be empty";
  }
  else if(firstname.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Firstname should not be more than 50 characters";
  }

  if($.trim(lastname)==""){
    if(str!="")
      str+= "<br/>";
    str += "Lastname should not be empty";
  }
  else if(lastname.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Lastname should not be more than 50 characters";
  }

  if($.trim(title)!=""){
    if(title.length >50)
    {
      if(str!="") str+= "<br/>";
      str += "Title should not be more than 50 characters";
    }
  }

  if($.trim(professionaltitle)!=""){
    if(professionaltitle.length >50)
    {
      if(str!="") str+= "<br/>";
      str += "Professional title should not be more than 50 characters";
    }
  }
   
  if($.trim(email)==""){
    if(str!="")
      str+= "<br/>";
    str += "Email Address should not be empty";
  }

 


  else if(!validateEmail((email))){
    if(str!="")
      str+= "<br/>";
    str += "Email Address not valid";
  }
  else if(email.length >50)
  {
    if(str!="") str+= "<br/>";
    str += "Email should not be more than 50 characters";
  }
   
  if(websiteurl != ""){
    if(!isWeburl(websiteurl)){
      if(str!="")
        str+= "<br/>";
      str += "Please enter valid site url";
    }
    else if(websiteurl.length >50)
    {
      if(str!="") str+= "<br/>";
      str += "Website URL should not be more than 50 characters";
    }
  }

   if(locationid==""){
    if(str!="")
      str+= "<br/>";
    str += "Please choose any location";
  }


  
  /* if($.trim(phone)=="" && $.trim(phone1)=="" && $.trim(phone2)==""){
    if(str!="")
      str+= "<br/>";
    str += "Phone or Mobile should not be empty";
  }
  else if(phone.length >50 || phone1.length >50 || phone2.length >50)
  {
      if(str!="") str+= "<br/>";
         str += "Phone/Fax/Mobile should not be more than 50 characters";
   }*/
 
  if (str != "") {
    styleStatusMessages(str, "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }else{
    $('#dialog').html('<div style="padding-top: 190px; padding-left: 250px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+'physician_locator/workflow',
      data : "groupid="+groupid+"&firstname="+(firstname)+"&lastname="+(lastname)+"&title="+encodeURIComponent(title)+"&professionaltitle="+encodeURIComponent(professionaltitle)+"&email="+encodeURIComponent(email)+"&websiteurl="+encodeURIComponent(websiteurl)+"&phone="+(phone)+"&phone1="+(phone1)+"&phone2="+(phone2)+"&locationid="+(locationid)+"&gender="+(radiogenderValue)+"&npid="+(npid),
      async : false,
      cache : false,
      success : function (msg) {
        if(msg=='Success'){
          reopen_dialog(520,470,"Invitation content");
          $.ajax({
            type : "POST",
            url : baseurl+'physician_locator/configure_email/specialty',
            cache : false,
            success : function (res) {
              $('#dialog').html(res);
              createDatePicker('exp_date', 1);
              $('#physician_id').val('workflow');
            },
            error : function (res) {
              handleRequestError(res);
            }
          });
        }else{
          $("#dialog").dialog("destroy");
          openAlertDialog(250,130,"Error", "Failure to create physician", "information");
        }
      }
    });
  }
}

function enter_handle(event){
  if(event.keyCode && event.keyCode==13){
    listpendinginvitees();
  }else if(event.which && event.which==13){
    listpendinginvitees();
  }
}

function listpendinginvitees(){
  var physician_fname  = $.trim($('#physician_firstname').val());
  var physician_lname  = $.trim($('#physician_lastname').val());
  var physician_email  = $.trim($('#physician_email').val());
  var physician_npid  = $('#physician_npid').val();
  var data="";
  if(physician_fname == '' && physician_lname =='' && physician_email == '' && physician_npid == ''){
    $('#dialog').scrollTop(0);
    styleStatusMessages("Please enter values in atleast one field", "statusMessage", "failure");
    resize_dialog(500, 320);
    return false;
  }else if(physician_email!="" && !validateEmail(physician_email)){
    $('#dialog').scrollTop(0);
    styleStatusMessages("Please enter valid email address", "statusMessage", "failure");
    resize_dialog(500, 320);
    return false;
  }else{
    if(physician_fname!='')
      data+='&physician_firstname='+ encodeURIComponent(physician_fname);
    if(physician_lname!='')
      data+='&physician_lastname=' + encodeURIComponent(physician_lname);
    if(physician_email!='')
      data+='&physician_email=' + encodeURIComponent(physician_email);
    if(physician_npid!='')
      data+='&physician_npid=' + encodeURIComponent(physician_npid);
    $('#dialog').html('<div style="padding-top: 100px; padding-left: 230px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
    $.ajax({
      type : "POST",
      url : baseurl+'physician_locator/pending_invitees',
      data: data,
      cache : false,
      success : function (res) {
        if(res.indexOf('No physician available with search criteria')>-1){
          resize_dialog(300, 130);
        }else{
          reopen_dialog(768,400,"Invite Physician");
        }
        $('#dialog').html(res);
      },
      error : function (res) {
        handleRequestError(res);
      }
    });
    return true;
  }
}

function activationchange_physicians(id,status){
  var pageno                    =  $("#hid_pageno").val();
  var physician_fname           =  $('#physician_fname').html();
  var physician_lname           =  $('#physician_lname').html();
  var physician_datesend        =  $('#physician_datesend').html();
  var physician_npid            =  $('#physician_npid').html();
  var physician_statuscode      =  status;


  $('#dialog').html('<div style="padding-top:90px; padding-left:210px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');

  $.ajax({
    type: "POST",
    url: baseurl + 'physician_locator/update/'+id,
    data: '&physician_fname='+ physician_fname + '&physician_lname=' + physician_lname + '&physician_datesend=' + physician_datesend + '&physician_npid=' + physician_npid + '&physician_statuscode=' + physician_statuscode,
    success: function(message){
      applyAction(pageno,$('#edit-apply').attr('actionitem'));
      reopen_dialog(500,260,"View Physician");
      viewphysiciandialog(id);
      return false;
    },
    error : function (res) {
      handleRequestError(res);
    }
  });

  return false;
}

function goback_search(){
  
  var physician_fname  = $.trim($('#physician_firstname').val());
  var physician_lname  = $.trim($('#physician_lastname').val());
  var physician_email  = $.trim($('#physician_email').val());
  var physician_npid  = $('#physician_npid').val();
  var data = "";
  if(physician_fname!='')
    data+='physician_firstname='+ encodeURIComponent(physician_fname);
  if(physician_lname!='')
    data+='&physician_lastname=' + encodeURIComponent(physician_lname);
  if(physician_email!='')
    data+='&physician_email=' + encodeURIComponent(physician_email);
  if(physician_npid!='')
    data+='&physician_npid=' + encodeURIComponent(physician_npid);
  $('#dialog').html('<div style="padding-top:150px; padding-left:310px;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading... Please Wait !!!" title="Loading... Please Wait !!!" border="0"></div>');
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/search',
    data: data,
    cache : false,
    success : function (res) {
      reopen_dialog(500,300,"Search Physician");
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function goback_physician(action){
  if(action=="workflow"){
    var groupid = $('#phy_groupid').val();
    add_physician_workflow(groupid);
  }else{
    listpendinginvitees();
  }
}
function confiure_email(){
  openDialog(phmanageautoreply, 0, 780, 510, "Manage Auto Reply");
}

function phmanageautoreply(id){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/configure_email',
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      fckeditor('edit-invite-message');
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}


function save_email_invitation(){

  var ph_firstname = $.trim($('#edit-invite-fname').val());
  var ph_email  = $.trim($('#edit-invite-femail').val());
  var ph_recipient = $.trim($('#edit-invite-recipient').val());
  var ph_subject   = $.trim($('#edit-invite-subject').val());
  var ph_status = $('#edit-invite-status').val();
  var ph_message   = ckeditor.getData();
  var refusestr = ph_message.substring(ph_message.length-7);
  if($.trim(refusestr)=="<br />"){
    ph_message = ph_message.substring(0,ph_message.length-7);
  }
  var str = "";
  if(ph_firstname==""){
    str+="From Name should not be empty";
  }
  if(ph_email==""){
    if(str!="")
      str+="<br/>";
    str+="From Email Address should not be empty";
  }else if(!validateEmail(ph_email)){
    if(str!="")
      str+="<br/>";
    str+="From Email Address not valid";
  }
  if(ph_recipient==""){
    if(str!="")
      str+="<br/>";
    str+="Reply to should not empty";
  }else if(!validateEmail(ph_recipient)){
    if(str!="")
      str+="<br/>";
    str+="Reply to is not valid email";
  }
  if(ph_subject==""){
    if(str!="")
      str+="<br/>";
    str+='Subject should not empty';
  }
  if(refusestr==""){
    if(str!="")
      str+="<br/>";
    str+='Message should not empty';
  }
  if(str!=""){
    $('#dialog').scrollTop(0);
    styleStatusMessages(str, "statusMessage", "failure");
    return false;
  }
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/configure_email/save',
    data: '&firstname='+ph_firstname+'&email='+ph_email+'&recipient='+ph_recipient+'&subject='+ph_subject+'&message='+encodeURIComponent(ph_message)+'&status='+ph_status,
    cache : false,
    success : function (msg) {
      if(msg == "Success"){
        $('#dialog').dialog('destroy');
        openAlertDialog(340,130,"Autoreply", "Autoreply is configured and updated successfully.","success");
      }
      else{
        $('#dialog').dialog('destroy');
        openAlertDialog(340,130,"Error", "Error in updating the email message");
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });

}

function get_manageautoreply_type(){
  var status = $('#edit-invite-status').val();
  $('#ajax_load').show();
  if(status=="Invited"){
    $('#plc_div').show();
  }else{
    $('#plc_div').hide();
  }
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/manage_reply/'+status,
    cache : false,
    success : function (res) {
      eval('var json='+res);
      $('#edit-invite-fname').val(json.Name);
      $('#edit-invite-femail').val(json.From);
      $('#edit-invite-recipient').val(json.Recipient);
      $('#edit-invite-subject').val(json.Subject);
      ckeditor.setData(json.Message);
      $('#ajax_load').hide();
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function invite_physician(){
  if($('input[name=radioList]').is(":checked") == false){
    styleStatusMessages("Please select atleast one physician", "statusMessage", "failure");
    resize_dialog(768,400+30);
    $('#dialog').scrollTop(0);
    return;
  }
  id = $('input:radio[name=radioList]:checked').val();

  var physician_fname  = $.trim($('#physician_firstname').val());
  var physician_lname  = $.trim($('#physician_lastname').val());
  var physician_email  = $.trim($('#physician_email').val());
  var physician_npid  = $('#physician_npid').val();
  var data="";
  if(physician_fname!='')
    data+='&physician_firstname='+ encodeURIComponent(physician_fname);
  if(physician_lname!='')
    data+='&physician_lastname=' + encodeURIComponent(physician_lname);
  if(physician_email!='')
    data+='&physician_email=' + encodeURIComponent(physician_email);
  if(physician_npid!='')
    data+='&physician_npid=' + encodeURIComponent(physician_npid);

  reopen_dialog(520,470,"Invitation content");
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/configure_email/specialty/'+id,
    data: data,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
      createDatePicker('exp_date', 1);
      $('#physician_id').val(id);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function email_template(){
  var id = $('#physician_id').val();
  var expdate = $.trim($('#exp_date').val());
  var email = $.trim($('#invitee_mail').val());
  var spl = $('#invite_specialty').val();
  var txt = $('#custom_txt').val();
  var err="";
  var lines = 0;
  if(expdate==''){
    err="Please select the expiration date";
    lines+=20;
  }
  if(email==""){
    if(err!="")
      err+="<br/>";
    err+="Please enter invitee email";
    lines+=20;
  }else if(!validateEmail(email)){
    if(err!="")
      err+="<br/>";
    err+="Invitee email is not valid";
    lines+=20;
  }
  if(spl=='' || spl==null){
    if(err!="")
      err+="<br/>";
    err+="Please select the specialty";
    lines+=20;
  }
  if(err!=""){
    styleStatusMessages(err, "statusMessage", "failure");
    resize_dialog(520,470+lines);
    return;
  }
  var str="";
  var cnt = $('#invite_specialty option').size();
  var obj = $('#invite_specialty').get(0);
  for(var i=0;i<cnt;i++){
    
    if(str!="")
      str+="~~@@";
    str += obj.options[i].value+"##!!"+obj.options[i].text;
   
  }
  reopen_dialog(600,350,"Invite preview");
  $.ajax({
    type : "POST",
    url  : baseurl+'physician_locator/configure_email/invite/'+id,
    data : "specialty="+str+"&date="+expdate+'&email='+email+'&custom_txt='+encodeURIComponent(txt),
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function sendinvitation(){
  var json = $('#json').val();
  $("#dialog").html('<div style="padding-top:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/configure_email/sendemail',
    data: 'json='+encodeURIComponent(json),
    cache : false,
    success : function (msg) {
      if(msg =='Success'){
        $('#dialog').dialog('destroy');
        openAlertDialog(380,170,"Success", "An email has been sent, inviting the person to be listed in the new physician registries<br/><br/>You will be notified via email when the invitee completes the invitation or allows the invitation to expire.", "success");
      }else{
        $('#dialog').dialog('destroy');
        openAlertDialog(350,130,"Information", msg);
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
  
}

var ckeditor;
function fckeditor(id){
  if(!ckeditor){
    ckeditor = CKEDITOR.replace(id,{
      skin : 'v2',
      resize_enabled:false,
      enterMode: Number(2),
      removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
    });
  }else{
    if (CKEDITOR.instances[id]) {
      CKEDITOR.remove(CKEDITOR.instances[id]);
    }
    ckeditor=null;
    ckeditor = CKEDITOR.replace(id,{
      skin : 'v2',
      resize_enabled:false,
      enterMode: Number(2),
      removePlugins : 'elementspath,save,forms,font,format,smiley,maximize,showblocks,about,stylescombo,pagebreak,flash'
    });
  }
  $('.ui-dialog').css("filter","");
}

function reloadPhysicianupdatorList (limit, page, action, counter, url, location) {
  //page loading animation
  $("#hid_totalRec").val(counter);
  ph_pagination_loading(location);

  //Call the AJAX functionality and return the result
  var sort = $('#hid_sort').val();

  var pno = $('#hid_pop_pageno').val();

  var physician_firstname = $('#physician_firstname').val();
  var physician_lastname  = $('#physician_lastname').val();


  if(action=="previous"){
    page = parseInt(pno,10)-1;
  }else if(action=="next"){
    page = parseInt(pno,10)+1;
  }

  //remove the checkall checkbox if selected
  if ($("#checkAll")) {
    $("#checkAll").attr('checked', false);
  }


  $.ajax({
    type : "POST",
    url : url+"?limit="+limit+"&page="+page+"&mode=ajax"+"&physician_firstname="+physician_firstname+"&physician_lastname"+physician_lastname+(sort!=""?"&sorting="+sort:""),
    async : true,
    cache : false,
    success : function (msg) {
      if (location == "page") {
        $("#listingResultset").html(msg);
      }
      else if (location == "popup") {
        $("#listingResultsetPopup").html(msg);
      }
      //create pagination links through AJAX
      var str = "";
      var to = page*limit;
      //modified if the counter is less while filtering the records
      if (to > counter) {
        counter = $("#hid_totalRec").val();
      }

      str += '<span>Showing <b>'+(counter>0?(page-1)*limit+1:0)+'</b> to <b>'+(to>counter?counter:to)+'</b> of <b>'+counter+'</b></span>';
      if (page > 1) {
        str += '<a href="javascript:void(0)" onclick = "reloadPhysicianupdatorList('+limit+', '+0+', \'previous\', '+counter+', \''+url+'\', \''+location+'\')" class="red"><< Previous</a>';
      }
      if (to < counter) {
        str += '<span class="red"> |</span><a href="javascript:void(0)" onclick = "reloadPhysicianupdatorList('+limit+', '+0+', \'next\', '+counter+', \''+url+'\', \''+location+'\')" class="red">Next >></a>';
      }

      if (location == "popup") {
        if ($("#pagingdivtoppopup")) $("#pagingdivtoppopup").html(str);
        if ($("#pagingdivbottompopup")) $("#pagingdivbottompopup").html(str);
        $('#hid_pop_pageno').val(page);
      }
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

//Pagination loading animation
function ph_pagination_loading (location){

  if (location == "popup") {
    $("#listingResultsetPopup").html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
    $("#pagingdivtoppopup").html("");
    $("#pagingdivbottompopup").html("");
  }
}

function show_physician_status(){
  location.href = baseurl+'physician_locator/view_invites';
  return false;
}

/*function physician_status_dialog(){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/physician_status',
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });

}*/
function editor_add_text(text){
  ckeditor.insertText(text);
}

function replace_email(status){
  if(status==true){
    var phy_email = $('#phy_email').val();
    $('#invitee_mail').val(phy_email);
  }else{
    $('#invitee_mail').val("");
  }
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
  return true;
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function clearCookie(name) {
  createCookie(name,"",-1);
}

function show_physician_details(id){
  openAlertBox(600,400,"View Physician", '<div style="padding-top:140px;padding-bottom:280px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/details/'+id+'/invite',
    cache : false,
    success : function (res) {
      openAlertBox(600,400,"View Physician", res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function add_criteria(id){
  
  var specialityname = $.trim($('#edit-specialityname').val());
  var specialitydesc = $.trim($('#edit-specialitydesc').val());
  
  if (specialityname == ""){
      
    resize_dialog(520, 290+20);
    styleStatusMessages("Please enter the Specialty Name", "statusMessage", "failure");
    //$('#edit-specialityname').val(specialityname);
    $('#dialog').scrollTop(0);
    return;
  }
  if (specialityname && specialityname.length > 50){

    resize_dialog(520, 290+20);
    styleStatusMessages("Specialty Name should not be more than 50 characters", "statusMessage", "failure");
    //$('#edit-specialityname').val(specialityname);
    $('#dialog').scrollTop(0);
    return;
  }
  if (specialitydesc){
    if (specialitydesc.length > 256){

      resize_dialog(520, 290+20);
      styleStatusMessages("Specialty Description should not be more than 256 characters", "statusMessage", "failure");
      //$('#edit-specialityname').val(specialityname);
      $('#dialog').scrollTop(0);
      return;
    }
  }


  var status = $('#edit-status').val();
  var desc = $('#edit-specialitydesc').val();
  var allow = $('#edit-invite').get(0).checked;
  reopen_dialog(650,490,"Edit Criteria");
 

  $.ajax({
    type : "POST",
    url  : baseurl+'physician_locator/add_criteria/'+id,
    data : 'specName='+encodeURIComponent(specialityname)+'&specDesc='+encodeURIComponent(desc)+'&status='+status+'&allow='+allow,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function addmore_criteria(){
  if($('#none_rec')){
    $('#none_rec').remove();
  }
  var tot = $('#div_criteria').children().length;
  
  
  var bg = "dark";
  if((tot+1)%2==0)
    bg = "light";
  var str = '<div class="row-'+bg+'"><div class="leftpane">'+
  '<span id="numdis" style="vertical-align:top;">'+(tot+1)+'.&nbsp;</span><textarea cols="86" rows="4"></textarea></div>'+
  '<div class="rightpane" style="padding-top:35px;padding-left:40px;"><a href="javascript:delete_criteria('+tot+');">Delete</a></div>'+
  '<div class="clearit" style="padding:0px;"></div></div>';
  $('#div_criteria').append(str);
}

var del_criteria = "";

function delete_criteria(pos){  
  openConfirmBox(function(){
     
    $('#alertdialog').dialog('destroy');
   
    var container = $('#div_criteria').children(':eq('+pos+')');
    container = container.children('.leftpane');
    container = container.children('input');
    var delId = container.val();
    $('#div_criteria').children(':eq('+pos+')').remove();
    if(delId>0){
      if(del_criteria!="")
        del_criteria +=",";
      del_criteria+=delId;
    }
    var cnt = 0;
    $('#div_criteria').children().each(function(){
      var bg = "row-light";
      if(cnt%2 == 0){
        bg = "row-dark";
      }
      var str_cnt = cnt+1;
      str_cnt = str_cnt+'. ';
      $(this).find("#numdis").html(str_cnt);
      $(this).attr('class',bg);
      $(this).children('.rightpane').children('a').attr('href','javascript:delete_criteria('+cnt+')');
      cnt++;
    });
    var tot = $('#div_criteria').children().length;
    if(tot==0){
      $('#div_criteria').html(' <div class="row-dark"><div class="leftpane"><span id="numdis" style="vertical-align:top;">1.&nbsp;</span><textarea cols="86" rows="4"></textarea></div><div class="rightpane" style="padding-top:35px;padding-left:40px;"><a href="javascript:delete_criteria(0);">Delete</a></div><div class="clearit" style="padding:0px;"></div></div>');
    }
  }, 300, 130, "Confirm Delete", "Do you want to delete this criteria?");
}

function save_criteria(id){
  var splid = $('#spl_id').val();
  var del_ids = del_criteria.split(",");
  
 
  var json="";
  var txtids="";
  var del_status = "";
  var bool = false;
  var lengbool = false;
  $('#div_criteria').children().each(function(){
    var txt = $(this).children('.leftpane').children('textarea').val();
    var id = $(this).children('.leftpane').children('input').val();
    txt = txt.replace(/\n/g,'<br/>');
    id=$.trim(id);
    
    if($.trim(txt)==""){
      bool = true;
    }
    if (txt.length > 256){
      lengbool = true;
    }
    if (id > 0){
      
      if($.inArray(id, del_ids)){
          
        if (txtids != "")
          txtids += "^^||^^";
        txtids += id;
            
        if (del_status != "")
          del_status += "^^||^^";
        del_status += "false";
        

        if(json !="")
          json+="^^||^^";
        json+= txt;
       

      }
    }else{
      if (txtids != "")
        txtids += "^^||^^";
      txtids += "0";
      
      if (del_status != "")
        del_status += "^^||^^";
      del_status += "false";
      
      if(json !="")
        json+="^^||^^";
      json+= txt;
      
    }
    
  });
  
  if (del_ids){
    $.each(del_ids, function(key, value) {
      if (value){
        if (txtids != "")
          txtids += "^^||^^";
        txtids += value;

        if (del_status != "")
          del_status += "^^||^^";
        del_status += "true";

        if(json !="")
          json+="^^||^^";
        json+= "del";
      }
    });
  }
  if (lengbool == true){
    resize_dialog(650,490+20);

    styleStatusMessages('Criteria should not be more than 256 characters', "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }
  if(bool==true){
    resize_dialog(650,490+20);
    
    styleStatusMessages('Please enter criteria', "statusMessage", "failure");
    $('#dialog').scrollTop(0);
    return;
  }
  
 
  $('#dialog').html('<div style="padding-top:150px;padding-bottom:150px;text-align:center;"><img src="'+baseurl+themeurl+'/images/ajax-loader.gif" alt="Loading..." /></div>');
  $.ajax({
    type : "POST",
    url  : baseurl+'physician_locator/save_criteria/'+(splid=='undefined'?'':splid),
    data : 'data='+encodeURIComponent(json)+'&txtid='+encodeURIComponent(txtids)+"&del="+encodeURIComponent(del_status),
    cache : false,
    success : function (res) {
      res = $.trim(res);
      if(res=="Success"){
        $('#dialog').dialog('destroy');
        openAlertDialog(300, 130, 'Success', 'Specialty saved successfully', 'success');
        var pageno   = $('#hid_pageno').val();
        applyspecialityAction(pageno, 'view_speciality');
        del_criteria = "";
      }else if(res=="Specialty name not unique"){
        reopen_dialog(520,290+30,"Create Specialty");
        $.ajax({
          type : "GET",
          url : baseurl+'physician_locator/create_speciality',
          cache : false,
          success : function (res) {
            $('#dialog').html(res);

            styleStatusMessages('Specialty Name already exists!', "statusMessage", "failure");
            $('#dialog').scrollTop(0);

          },
          error : function (res) {
            handleRequestError(res);
          }
        });
      /*$.ajax({
          type : "GET",
          url  : baseurl+'physician_locator/add_criteria/'+(id=='undefined'?'':id),
          cache : false,
          success : function (res) {
            $('#dialog').html(res);
            styleStatusMessages('Specialty name already exist', "statusMessage", "failure");
            $('#dialog').scrollTop(0);
          },
          error : function (res) {
            handleRequestError(res);
          }
        });*/
      }else{
        resize_dialog(300, 150);
        $('#dialog').dialog('destroy');
        openAlertDialog(300, 130, 'Information', res,'information');
      }
    },
    error : function (res) {
       
      handleRequestError(res);
    }
  });
}
function cancel_criteria(id){
  var splid = $('#spl_id').val();
  if (splid == ""){
    $('#dialog').dialog('destroy');
    $("#cancelId").val("cancel");
    openDialog(addspecialitydialog, 'cancel', 520,290, 'Create Specialty');
       
  }else{
    editSpeciality(splid);
  }
}

function invitationviewdialog(physicianformdata){
  $.ajax({
    type : "POST",
    url : baseurl+'physician_locator/physician_invitation',
    data: "physician="+encodeURIComponent(physicianformdata),
    async : true,
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    },
    error : function (res) {
      handleRequestError(res);
    }
  });
}

function HandoffSpecialities(){
  openDialog(Handoffspecialitiesdetails,'1',500,200,'Handoff Specialties');
}

function Handoffspecialitiesdetails(id){
  $.ajax({
    type : "GET",
    url : baseurl+'physician_locator/handoff_specialities',
    cache : false,
    success : function (res) {
      $('#dialog').html(res);
    }
  });
}
function checkbox_invite(){
  // If checked
  if ($("#edit-check-invite").is(":checked")){
    $("#spec_create_createris").hide();
    $("#spec_create").show();
  }else{
    $("#spec_create").hide();
    $("#spec_create_createris").show();
  }
}
function changeCriteriaedit(){
  // If checked
 
  if ($("#edit-invite").is(":checked")){
    $("#edit_cre").show();
    $("#edit-resp-criteria").show();
    $("#edit_save").hide();
   
  }else{
    $("#edit_cre").hide();
    $("#edit-resp-criteria").hide();
    $("#edit_save").show();
  }
}

function changeStateForUs()
{
  if($("#edit-country").val() == "US"){
    $("#usstates").show();
    $("#otherstates").hide();
  }
  else{
    $("#usstates").hide();
    $("#otherstates").show();
  }
}